← Back to jQuery Course | Chapter 5: DOM Manipulation | Lesson 1 of 9

Getting and Setting Text HTML and Values

Use text() to read the plain text inside an element.

Reading Text

The text() method reads back the plain-text content of an element, stripping out any HTML tags found inside it -- so a <strong> tag inside the element is invisible to text(), only its wording is returned.

Example: Reading Text

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div id="box"><strong>Bold</strong> text</div>
    <script>
      console.log($("#box").text());
    </script>
  </body>
</html>

Setting Text

Calling text() with a string argument replaces an element's entire content with that plain text, automatically escaping any HTML-special characters so they display literally rather than being parsed as markup.

Example: Setting Text

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div id="box"></div>
    <script>
      $("#box").text("<b>Not bold</b>");
    </script>
  </body>
</html>

Reading HTML

html() reads back an element's full inner markup, including any nested tags, which is what you want when you need to inspect or copy structured content rather than just its wording.

Example: Reading HTML

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div id="box"><strong>Bold</strong> text</div>
    <script>
      console.log($("#box").html());
    </script>
  </body>
</html>

Setting HTML

Calling html() with a string argument replaces an element's contents with that markup, parsing it as real HTML -- unlike text(), any tags in the string become live elements in the page.

Example: Setting HTML

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div id="box"></div>
    <script>
      $("#box").html("<strong>Now bold</strong>");
    </script>
  </body>
</html>

Getting and Setting Values

val() reads or sets the current value of a form control like an input, select, or textarea, which is distinct from text() and html() since a form control's displayed value isn't stored as regular element content.

Example: Getting and Setting Values

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <input id="name" type="text" value="Alice">
    <script>
      console.log($("#name").val());
      $("#name").val("Bob");
    </script>
  </body>
</html>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.