Showing posts with label jQuery HTML Manipulation. Show all posts
Showing posts with label jQuery HTML Manipulation. Show all posts

Thursday, 15 December 2011

jQuery HTML Manipulation


1. Changing HTML Content

jQuery contains powerful methods (functions) for changing and manipulating HTML elements and attributes.

  • $(selector).html(content)

The html() method changes the contents (innerHTML) of matching HTML elements.

syntax:

$("p").html("manipulate"); 

Example:

 <html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").html("manipulate");
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>

2. Adding HTML content

The append() method appends content to the inside of matching HTML elements.
  • $(selector).append(content)

The prepend() method "prepends" content to the inside of  matching HTML elements.
  • $(selector).prepend(content)

syntax:

$("p").append(" addcontent"); 

Example: 

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").append(" <b>for addcontent</b>.");
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>

3. Adding HTML content: after(), before()

The after() method inserts HTML content after all matching elements.
  • $(selector).after(content)
The before() method inserts HTML content before all matching elements. 
  • $(selector).before(content)

syntax:

$("p").after(" content-add.");

Example:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").after(" to add content.");
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>

jQuery HTML Manipulation Methods:

Function Description
1. $(selector).html(content) Changes the (inner) HTML of selected elements
2. $(selector).append(content) Appends content to the (inner) HTML of selected elements
3. $(selector).after(content) Adds HTML after selected elements