Working with HTML Elements
One of jQuery’s most useful time-saving tricks is to manipulate the content of page elements. The html() and text() methods allow you to get and set the content of any elements you’ve selected using the previous statements, while attr() lets you get and set the values of individual element attributes. Let’s see some examples.
html()
The html() method gets the HTML of any element or collection of elements. It works pretty much like JavaScript’s innerHTML:
var htmlContent = $("#elem").html(); /* variable htmlContent now contains all HTML (including text) inside page element with id "elem" */
Using similar syntax, you can set the HTML content of a specified element or collection of elements:
$("#elem").html("<p>Here is some new content.</p>"); /* page element with id "elem" has had its HTML content replaced*/
text()
If you only want the text content of an element or collection of elements, without the HTML, you can use text():
var textContent = $("#elem").text(); /* variable textContent contains all the text (but not HTML) content from inside a page element with id "elem" */
Once more you can change the text content of the specified element(s):
$("#elem").text("Here is some new content."); /* page element with id "elem" has had its text content replaced*/
If you want to append content to an element, rather than replacing it, you can use the following:
$("#elem").append("
Here is some new content.
"); /* keeps current content intact, but adds the new content to the end */
And likewise:
here to view code image $("div").append("<p>Here is some new content.</p>"); /* add the same content to all <div> elements on the page. */
attr()
When passed a single argument, the attr() method gets the value for the specified attribute:
var title = $("#elem").attr("title");
If applied to a set of elements, it returns the value for only the first element in the matched set.
You can also pass a second argument to attr() to set an attribute value:
$("#elem").attr("title", "This is the new title");