jQuery Set Content

In the previous lesson you learned to read content with text(), html(), and val(). The great news is that the exact same methods let you change content too. All you have to do is pass a value into them, and jQuery switches from reading to writing.

The same methods, now in set mode

When you give a method an argument, jQuery updates every element that your selector matched. This is one of jQuery's most convenient features: you can change many elements at once without writing a loop yourself.

  • text("...") sets plain text and escapes any HTML you pass, so tags show up as literal characters.
  • html("...") sets inner HTML and actually renders any tags you include.
  • val("...") sets the value of form fields such as inputs and textareas.

Setting text and HTML

The difference between text() and html() matters even more when writing. If you pass a string containing a tag to text(), the tag is displayed as-is. Pass that same string to html() and the browser treats it as real markup.

Writing with text() and html()

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<p id="a">Old text</p>
<p id="b">Old text</p>

<script>
$(document).ready(function() {
  // Shows the tag as plain characters
  $("#a").text("I am <b>bold</b>");

  // Renders the word bold in bold
  $("#b").html("I am <b>bold</b>");
});
</script>

</body>
</html>

Setting values and using a callback

All three methods also accept a callback function. jQuery passes the callback the index of the current element and its existing content, and whatever you return becomes the new content. This is perfect when the new value should build on the old one.

A callback that keeps the old value

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<p id="msg">Hello</p>

<script>
$(document).ready(function() {
  $("#msg").text(function(index, oldText) {
    return oldText + ", welcome back!";
  });
  // Paragraph now reads: Hello, welcome back!
});
</script>

</body>
</html>
Note: Only use html() with content you trust. If you drop text typed by a user straight into html(), any script tags in it could run. When you just need plain text, prefer text() because it escapes the content for you.
CallEffect
text("Hi")Replaces content with the plain text Hi
html("<i>Hi</i>")Replaces content and renders Hi in italics
val("Hi")Sets the value of the matched form field to Hi

Once you are comfortable replacing content, the natural next step is adding brand new elements to the page, which is exactly what the next lesson covers.

Exercise: jQuery Set Content

What happens if you call .text("<b>Hi</b>") to set an element's content?