Saturday, July 9, 2011

Adding, Removing, and Appending Elements and Content

There are a number of ways to manipulate groups of elements with jQuery, including manipulating the content of
those elements (whether text, inline elements, etc).

Get the HTML of any element (similar to innerHTML in JavaScript):
var myElementHTML = $("#myElement").html();// variable contains all HTML (including text) inside #myElement.

If you don't want to access the HTML, but only want the text of an element:
var myElementHTML = $("#myElement").text();// variable contains all text (excluding HTML) inside #myElement
Using similar syntax to the above two examples, you can change the HTML or text content of a specified element:
$("#myElement").html("
This is the new content.
");// content inside #myElement will be replaced with that specified
$("#myElement").text("This is the new content.");// text content will be replaced with that specified

To append content to an element:
$("#myElement").append("
This is the new content.
");// keeps content intact, and adds the new content to the end
$("p").append("This is the new content.
");// add the same content to all paragraphs

jQuery also offers use of the commands appendTo(), prepend(), prependTo(), before(), insertBefore(), after(), and insertAfter(), which work similarly to append() but with their own unique characteristics that go beyond the scope of this simple tutorial.

No comments:

Post a Comment