Get the Text of an HTML Element in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 5, 2024
3 min

banner

# Get the Text of an HTML Element in JavaScript

Use the textContent property to get the text of an HTML element, e.g. const result = element.textContent.

The textContent property will return the text content of the element and its descendants. If the element is empty, an empty string is returned.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <div id="container"> One, <span style="background-color: salmon">Two</span>, Three </div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const container = document.getElementById('container'); // ๐Ÿ‘‡๏ธ One, Two, Three console.log(container.textContent); // ๐Ÿ‘‡๏ธ One, Two, Three console.log(container.innerText);

get text of div

The code for this article is available on GitHub

We used the textContent property to get the text content of the div and its descendants.

The property returns the concatenation of the text content of every child node, excluding comments.

If the div element were empty, the property would return an empty string.

# Handling leading and trailing spaces when using textContent

You might get leading or trailing spaces when using textContent depending on the structure of your HTML.

If you need to remove any leading or trailing spaces, use the trim() method.

index.js
const container = document.getElementById('container'); // ๐Ÿ‘‡๏ธ "One, Two, Three" const result = container.textContent.trim();
The code for this article is available on GitHub

The String.trim() method removes the leading and trailing whitespace from a string and returns a new string, without modifying the original string.

The trim() method removes all whitespace characters including spaces, tabs and newlines.

# Using textContent vs innerText

The code snippet also showed that we can use the innerText property to get the text content of an element and its descendants.

index.js
const container = document.getElementById('container'); // ๐Ÿ‘‡๏ธ One, Two, Three const result = container.innerText;

However, there are some important differences between the textContent and innerText properties:

  1. textContent gets the content of all elements, including script and style elements, whereas innerText only gets the content of "human-readable" elements.
  2. innerText is aware of styling and does not return the text of hidden elements, whereas textContent does not take styles into consideration.
  3. using textContent can prevent cross-site scripting attacks.
innerText takes CSS styles into account, so when the property is accessed, a reflow is triggered to ensure the styles are up-to-date.

Reflows can be expensive and should be avoided when possible.

When you use textContent and innerText to set the element's text content, the element's child nodes get removed.

When using the textContent and innerText properties to update the text content of the element, the child nodes of the element get replaced with a single text node with the provided string value.

If you need to set an element's text content, you should use the insertAdjacentText() method instead.

index.js
const container = document.getElementById('container'); // โœ… Update the text content of the element container.insertAdjacentText('beforeend', ', Four'); // โœ… Update the HTML content of the element container.insertAdjacentHTML( 'beforeend', '<span style="background-color: coral">, Five</span>', );
The code for this article is available on GitHub

The insertAdjacentText method doesn't remove the child nodes of the element it was called on.

The insertAdjacentText method takes the following 2 parameters:

  1. position - the position relative to the element where the text should be inserted. Can be one of the following 4:
  • beforebegin - before the element itself.
  • afterbegin - just inside the element, before its first child.
  • beforeend - just inside the element, after its last child.
  • afterend - after the element itself.
  1. data - the string from which to create a new text node to insert at the given position.
In the example, we added a string inside of the element, after its last child. However, you can pass a different first argument to the method depending on your use case.

The example also shows how to use the insertAdjacentHTML method to insert HTML into the div element.

The insertAdjacentHTML method takes the same first parameter as insertAdjacentText.

index.js
const container = document.getElementById('container'); // โœ… Update the HTML content of an element container.insertAdjacentHTML( 'beforeend', '<span style="background-color: coral">, Five</span>', );
The code for this article is available on GitHub

However, note that you shouldn't use user-generated input without escaping it, because that leads to a cross-site scripting vulnerability.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev