How to set or get the text/html of an element

A very common task of JavaScript is to change the page contents. This can be simple text changes to existing page elements, or adding new HTML elements. jQuery provides us with two methods for this - the text() and html() methods. If we just want to set some text, we use the text() method. The value we want to set is included as a parameter to the method. The same with the html() method - except it's parameter can be a string of HTML or a reference to an HTML element.

//change the text of a target paragraph
$("#targetParagraph").text("This is new text");
//
//change the HTML of a target div
$("#targetDIV").html("<ul><li>Item One</li><li>Item 2</li></ul>");

Sometimes we want to look at the existing text or HTML of an element and use it to do further processing. Getting these values is as simple as calling the text() or html() method without any parameters. For instance, if we wanted to show an alert for these values we might do this:

alert( $("#targetParagraph").text() );
alert( $("#targetDIV").html() );

It should be noted that both the .text() and .html() methods will return strings. Even if our element only contains a numeric value, we will get a string of that nuber back (i.e. "3.14" vs 3.14). This is a problem when we do math. If math calculations are being done with these values, then we'll have to extract the numbers via the native JavaScript function of parseInt or parseFloat.

<div id="one">1</div>
<div id="two">2.5</div>
. . .
var total = $("#one").text() + $("#two".text();
alert( total );
// resuts in "12.5";
//
var total = parseFloat( $("#one").text() ) + parseFloat( $("#two").text() );
alert( total );
//results in 3.5 as expected.