Accessing Element Content with jQuery

Explains how to use jQuery's html(), text() and val() methods for reading and changing HTML element contents and values.

jQuery logoNow that you know how to select HTML page elements in jQuery, you can start to do useful things with those elements. In this tutorial you'll look at how to work with the contents of an element.

jQuery lets you work with HTML elements and element content in many different ways. For example, you can add new elements inside, around, before, or after existing elements; you can replace an element with another element (or elements); and you can read or change an element's contents. Often the line between working with elements and element content is blurred — for example, when you add new elements inside an existing element, you're effectively adding to that element's contents.

You'll look at adding, removing and replacing elements in a later tutorial. In this tutorial you'll learn about 3 jQuery methods designed for working directly with the contents of an element:

  • html() for reading and changing the HTML contents of an element
  • text() for reading and changing the text contents of an element
  • val() for reading and changing form field values

As you'll see, these methods make it very easy to read or change the raw contents or value of any HTML element.

Working with HTML content: html()

jQuery's html() method lets you read the HTML contents of an element as a string, or replace the element's contents with a new HTML string.

Reading the HTML contents of an element

To retrieve an element's HTML contents, first select the element as a jQuery object, then call the html() method on the object. For example, the following code selects the p (paragraph) element in the page, then calls html() to display the HTML contents of the element:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  alert( $('p').html() );
}

</script>
</head>
<body>
  <p>Here's a paragraph of text containing a <a href="#">link</a>.</p>
</body>
</html>

The above code pops up an alert box displaying the raw HTML markup inside the element, as follows:


Here's a paragraph of text containing a <a href="#">link</a>.

If you call html() on multiple selected elements, it only returns the contents of the first element in the set.

Replacing the HTML contents of an element

As well as reading the HTML contents of an element, you can replace an element's contents with a new string of HTML markup. Here's an example that replaces a paragraph inside a div element with a whole new heading and paragraph:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  $('#myDiv').html('<h2>A New Heading</h2><p>Here\'s some new text containing <a href="#">another link</a>.</p>');
}

</script>
</head>
<body>
  <div id="myDiv">
    <p>Here's a paragraph of text containing a <a href="#">link</a>.</p>
  </div>
</body>
</html>

After running the above code, the page content changes to reflect the new markup, displaying the following:


A New Heading

Here's some new text containing another link.

If you call html( newHTML ) on a set of several selected elements then each element's content is replaced with the string newHTML.

Using a function to replace the HTML contents of an element

Instead of passing a replacement string to html(), you can pass a callback function. The function should accept 2 arguments:

  • The index position of the current element in the set (starting from zero)
  • The old HTML contents of the current element

The return value of the function is then used as the replacement HTML.

This approach is handy if you want to replace the content of multiple elements based on their position or existing content (or both). Here's an example that adds an item number to the start of each h2 heading in the page:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  $('h2').html( insertNumbers );
}

function insertNumbers( index, oldHTML ) {
  return (index+1) + ". " + oldHTML;
}

</script>
</head>
<body>
  <h2>First heading</h2>
  <h2>Second heading</h2>
  <h2>Third heading</h2>
</body>
</html>

After running the above code, the page displays:


1. First heading
2. Second heading
3. Third heading

Working with plain text content: text()

While html() lets you read and change the raw HTML contents of an element — including any HTML tags — the text() method works with plain text content only:

  • When you read the contents of an element using text(), all HTML tags are stripped out.
  • When you use text() to replace the contents of an element, any HTML tags in the replacement string are encoded so that they are displayed in the page.

Reading text content

You use text() in much the same way as html(). The following example selects a paragraph, then displays its text content:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  alert( $('p').text() );
}

</script>
</head>
<body>
  <p>Here's a paragraph of text containing a <a href="#">link</a>.</p>
</body>
</html>

The above code displays the following alert box — notice how the <a> and </a> tags have been stripped from the content:


Here's a paragraph of text containing a link.

As with html(), text() only reads the contents of the first element in a set of elements.

Replacing text content

text() works like html() when it comes to replacing content, too. The only difference is that any HTML tags in the text string are encoded. This means that the tags are displayed in the page as they are, rather than being used to create new elements.

Here's an script based on the previous html() replacement example that replaces the contents of a paragraph with some new plain text content:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  $('#myDiv').text('<h2>A New Heading</h2><p>Here\'s some new text containing <a href="#">another link</a>.</p>');
}

</script>
</head>
<body>
  <div id="myDiv">
    <p>Here's a paragraph of text containing a <a href="#">link</a>.</p>
  </div>
</body>
</html>

Here's what the resulting page looks like. Notice that, this time, the <h2>, <p> and <a> tags are simply displayed in the page, rather than being used to create the heading, paragraph, and link:


<h2>A New Heading</h2><p>Here's some new text containing <a href="#">another link</a>.</p>

Using a function to replace text content

As with html(), you can use a function with text() if you want to replace an element's text content based on its position or its existing content. Here's the earlier "numbered headings" example, modified to use text() instead of html() and using a '>' symbol for the separator instead of a dot:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  $('h2').text( insertNumbers );
}

function insertNumbers( index, oldText ) {
  return (index+1) + " > " + oldText;
}

</script>
</head>
<body>
  <h2>First heading</h2>
  <h2>Second heading</h2>
  <h2>Third heading</h2>
</body>
</html>

This produces the following result:


1 > First heading
2 > Second heading
3 > Third heading

If you run the above code and view the HTML source, you'll see that text() has encoded the '>' symbols as '&gt;'.

Working with form field values: val()

The last method you'll look at is val(). This behaves much like text(), except that it reads or changes the value of a form field, rather than the text contents of an element.

Here's an example that shows how to both read and change form field values with val():


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$( init );

function init() {
  var output = "Product: " + $('#product').val() + "\n";
  output += "Quantity: " + $('#quantity').val() + "\n";
  output += "Express Shipping: " + $('input:radio[name=express]:checked').val() + "\n";
  alert( output );
  $('#product').val( "megawidget" );
  $('#quantity').val( 4 );
  $('#expressNo').attr('checked', true);
}

</script>
</head>
<body>
  <form method="post" action="" />
    <div>
      <label>Product:</label>
      <select id="product" name="product">
        <option value="superwidget">SuperWidget</option>
        <option value="megawidget">MegaWidget</option>
        <option value="wonderwidget">WonderWidget</option>
      </select>
      <br />
      <label>Quantity:</label>
      <input type="text" id="quantity" name="quantity" value="3" />
      <br />
      <label>Express Shipping:</label>
      <input type="radio" id="expressYes" name="express" value="yes" checked="checked" /> Yes
      <input type="radio" id="expressNo" name="express" value="no" /> No
    </div>
  </form>
</body>
</html>

First, the code pops up an alert box displaying the default values of the form's select list, input text field and radio button group:


Product: superwidget
Quantity: 3
Express Shipping: yes

Then the code changes the selected product to "MegaWidget", the quantity to 4, and the Express Shipping option to "no".

In the above example, I checked the #expressNo radio button by calling the attr() method to set the button's checked attribute, since val() can't change the checked status of radio buttons or checkboxes.

You'll learn more about reading and setting element attributes in the next tutorial.

Here are some useful things to remember when using val():

  • You can use val() to read or change the selected option in select lists. As you can see in the above code, you can change the selected widget simply by passing the new value to val(). (Of course, that value has to exist as an option within the list.)
  • You can read all selected option values in a multiple select list. If you do this, val() returns an array of the selected values. (Unfortunately it doesn't work the other way — you can't pass an array to val() to set multiple options.)
  • You can get the value of the selected radio button in a group. As shown in the above example, you can use val() in combination with the :checked selector to determine the value of the selected button. (This trick sort of works with checkboxes too; however, val() will only return the value of the first checkbox in the selected set.)
  • You can change multiple form field values with a function. Just like html() and text(), you can pass a function to val() to change multiple field values based on their index position and/or current values.

Summary

In this article you've explored 3 jQuery methods for manipulating the contents of an HTML element:

  • html(), which lets you read or replace the HTML markup inside an element
  • text(), which is similar to html() but works with plain text content, and
  • val(), which is designed to read and change the values of form fields.

These methods are handy for those times when you need to read or change the entire contents of an HTML element. In future tutorials, I'll show how to use other jQuery methods to add and remove individual elements inside an element, as well as how to work with an element's attributes.

Happy coding!

Follow Elated

Related articles

Responses to this article

There are no responses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page