Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 56 ยท Manipulating the DOM

Getting and Setting Content

Read and change element content with jQuery .text(), .html() and .val(), use setter functions, and learn why .html() with user input is an XSS risk.

Selecting and traversing find elements; now it is time to change them. The most common change is content: the words in a heading, the markup in a message box, the value in a form field. jQuery handles all three with three methods that share one design: called with no argument they read, called with an argument they write. These are known as getter and setter forms.

  • .text() reads or writes plain text.
  • .html() reads or writes HTML markup.
  • .val() reads or writes the value of form controls.

Choosing the right one is mostly a question of security and of what the element is. This lesson explains each, shows how setter functions let you compute content per element, and ends with the XSS trap that catches many beginners.

Three methods, three jobs

.text() Plain words. Markup is shown as text.
.html() Markup is parsed into elements.
.val() The value of inputs, selects and textareas.
1 / 2

.text(): plain text

Without arguments, .text() returns the combined text of all elements in the set, including their descendants. With an argument it replaces the content of every element with that text.

JavaScript
$("h1").text();                 // reads the heading's words
$("h1").text("Welcome back");   // sets it
$("li").text();                 // all li texts joined into one string

The setter treats its argument as text, never as markup. Characters like < and & are escaped for you, so $("p").text("<b>hi</b>") shows the literal characters <b>hi</b> on the page. That makes .text() the safe default whenever you show anything that did not come from you.

When it reads, .text() ignores CSS: hidden elements still contribute their text, and <script> and <style> bodies are included if they are inside the selected elements.

.html(): markup

.html() reads the inner HTML of the first element in the set, and writes inner HTML to every element.

JavaScript
$("#box").html();                                  // "<b>Hello</b> there"
$("#box").html("<em>New</em> content");            // parsed into elements
$("#box").html("");                                // empties the box

Because the new content is parsed, it can contain elements, attributes and even event-handler attributes. That is the reason for the security rules later in this lesson. Also note that .html() replaces the old children, and jQuery cleans up the data and handlers it attached to them.

For adding without replacing, use the insertion methods in Inserting Content.

.val(): form values

.val() reads or writes the value of <input>, <textarea> and <select> elements, and handles checkboxes and multi-selects in its own ways (covered in form controls).

JavaScript
$("#name").val();             // current text in the field
$("#name").val("Ada");        // set it
$("#name").val("").focus();   // clear and focus (setters chain)

.val() always returns a string for text inputs, even for <input type="number">. Convert with Number() when you need arithmetic. For a <select multiple> it returns an array. On an element without a value, such as a <div>, it returns undefined; use .text() there.

Setter functions

All three setters accept a function instead of a value. jQuery calls it for each element with the index and the old content, and uses what you return. This replaces a loop plus .each() for the common case of "new content depends on old content".

JavaScript
// Number every list item
$("li").text(function (index, oldText) {
  return (index + 1) + ". " + oldText;
});

// Trim every field
$("input").val(function (i, old) { return old.trim(); });

The function's this is the element, so you can read attributes too: .text(function () { return $(this).data("label"); }).

text, html and val side by side

textContent, innerHTML and jQuery

The native equivalents are element.textContent, element.innerHTML and input.value. They behave almost the same, with a few differences:

Task jQuery Native DOM
Read text $(el).text() (all elements joined) el.textContent (one element)
Set text on many elements $("li").text("x") loop over a NodeList
Read HTML $(el).html() (first element) el.innerHTML
Set HTML $(el).html(str) (runs <script> tags in the string) el.innerHTML = str (does not run scripts)
Value $(el).val() el.value

One difference deserves attention: .html(str) executes scripts inside the string in some situations, while innerHTML does not. That is another reason to treat .html() with respect.

The XSS trap

Suppose a page shows a comment typed by a visitor:

JavaScript
// DANGEROUS
$("#comment").html(userInput);

If userInput is <img src=x onerror="stealCookies()">, the browser creates an image, fails to load it and runs the onerror code. This is cross-site scripting (XSS), and it is one of the most common web vulnerabilities. The same applies to values from the URL, from localStorage, from a server response or from a form.

The rules are simple:

  1. If you show text, use .text(). It escapes everything.
  2. If you must build markup from data, create elements and set their text separately, or escape the values first.
  3. Use .html() only with strings you wrote yourself.

The playground below shows the difference. The "payload" tries to run code through a broken image. It only fires when passed to .html(); inside the sandboxed preview it merely sets a message, so nothing harmful can happen.

Why .html() with user input is risky

Note also that $() can create elements from a string beginning with <, so passing user input directly into $() is another way in. Best practices returns to this.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $('li').text() return when there are three list items?

    As a getter, .text() joins the text of every element in the set. .html() and .val() read only the first element.
  2. 2. Which statement is safe to use with text typed by a visitor?

    .text() escapes markup, so injected tags appear as plain characters. The others parse the visitor's string as HTML.
  3. 3. What are the arguments of a setter function such as .text(function (a, b) {...})?

    jQuery passes the element's index first and its current content second; this is the element.
  4. 4. What type does $('input[type=number]').val() return?

    Form values are strings. Use Number() or parseFloat() before doing arithmetic.

Summary

  • .text(), .html() and .val() read when called without arguments and write when given one; setters return the jQuery object for chaining.
  • .text() reads all elements joined; .html() and .val() read the first element only; every setter writes to all elements.
  • .text(value) escapes markup and is the safe choice for untrusted data; .html(value) parses markup and must only receive strings you control.
  • A setter function receives (index, oldValue) and returns the new content, with this as the element.
  • .val() returns strings (arrays for multi-selects) and works on form controls only.
  • Compared with native code, jQuery saves loops over multiple elements, but the safety rules are the same as for textContent and innerHTML.

Next: Attributes and Properties explains .attr() versus .prop() and why the difference matters for checkboxes.