Text and HTML
Element content is read and changed with two methods: text() works with text, html() with the markup inside the element. The same method reads the value when called without an argument and writes it when given one.
Reading and writing text
<h1>My tasks</h1>
<p id="counter">Tasks: 0</p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
console.log($('h1').text()); // My tasks
$('#counter').text('Tasks: 3');
</script>The paragraph now reads "Tasks: 3". This pattern, one method for both reading and writing, appears everywhere in jQuery: in html(), attr(), css(), val().
Markup inside an element
html() returns the HTML of the content and accepts a string with tags:
<p id="status">Nothing selected</p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$('#status').html('Selected: <strong>Buy bread</strong>');
console.log($('#status').html()); // Selected: <strong>Buy bread</strong>
</script>The task name appears in bold: the browser parsed the strong tag.
text() versus html()
text() inserts the string as is: angle brackets are shown on the page instead of becoming tags:
<p id="a"></p>
<p id="b"></p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$('#a').text('<b>Important</b>');
$('#b').html('<b>Important</b>');
</script>The first paragraph shows the tags, the second shows a bold word.
Reading from several elements
When the set has several elements, the methods behave differently:
| Call | Result |
|---|---|
$('li').text() | The text of all items joined into one string |
$('li').html() | The HTML of the first item only |
$('li').text('...') | Writes the text into every item |
A new value from the old one
Instead of a string you can pass a function. It receives the element index and the current value and returns the new one:
<ul>
<li>Buy bread</li>
<li>Call Oleg</li>
</ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$('li').text(function (index, oldText) {
return (index + 1) + '. ' + oldText;
});
</script>The items are numbered: "1. Buy bread", "2. Call Oleg".
The same in plain JavaScript
text() corresponds to the textContent property, html() to the innerHTML property.
Common mistake
Inserting user input with html(). If a task name contains <img src=x onerror="...">, the browser runs that code: this is an XSS vulnerability. Output text from form fields only with text().