text, html and val

Read and change the content of elements and form fields.

Syntax$(el).text(); $(el).html(value); $(input).val();

Three core methods read or set content. Called with no argument they get; called with a value they set.

MethodWorks with
.text()plain text (HTML is escaped)
.html()inner HTML markup
.val()form field values

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A live preview panel uses .html() to render rich text typed in a markdown editor beside the input.
  • A character counter reads .val() on every keyup to calculate how many characters remain in a tweet field.
  • A search results page updates a .text() span with the number of matching items returned from an AJAX query.

More examples

Read and write text content

.text() with no argument reads the content; with an argument it replaces it — both on the same element.

Example · html
<p id="msg">Original text</p>
<button id="change">Change</button>
<p>Current: <span id="read"></span></p>
<script>
$(function () {
  $("#read").text($("#msg").text());
  $("#change").click(function () {
    $("#msg").text("Updated text!");
    $("#read").text($("#msg").text());
  });
});
</script>

Inject HTML markup with .html()

.html() sets the inner HTML of the element, parsing the string as markup unlike .text() which escapes it.

Example · html
<div id="card"></div>
<button id="render">Render card</button>
<script>
$(function () {
  $("#render").click(function () {
    $("#card").html(
      "<h3>Product Name</h3><p>Price: <strong>$29</strong></p>"
    );
  });
});
</script>

Read and set form field value

.val() reads the current value of the input and returns it as a string for use in logic or display.

Example · html
<input id="username" type="text" value="Alice" />
<button id="greet">Greet</button>
<p id="out"></p>
<script>
$(function () {
  $("#greet").click(function () {
    var name = $("#username").val();
    $("#out").text("Hello, " + name + "!");
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.