Getting and Setting Element Content

The text() and html() methods query and set the plain-text or HTML content of an element. When invoked with no arguments, text() returns the plain-text content of all descendant text nodes of all matched elements. This works even in browsers that do not support the textContent or innerText properties.

If you invoke the html() method with no arguments, it returns the HTML content of just the first matched element. jQuery uses the innerHTML property to do this: x.html() is effectively the same as x[0].innerHTML.

If you pass a string to text() or html(), that string will be used for the plain-text or HTML-formatted text content of the element, and it will replace all existing content. As with the other setter methods we’ve seen, you can also pass a function, which will be used to compute the new content string:

var t = $("head title").text(); // Get document title
var hdr = $("h1").html()        // Get html of first <h1>
// Give each heading a section number
$("h1").text(function(n, current) {   
    return "§" + (n+1) + ": " + current
});

Get jQuery Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.