How do i get text content in html?

You are here: Home / How To / How to Get HTML Elements with textContent in JavaScript

This is a short instruction on how to identify an HTML element based on a specific string that can be searched using textContent property.

It’s best to demonstrate the method with an example. Using the HTML page below, we are going to search for a text “Search This!” and select the whole row and change the background color to maroon.

First of all, we are going to create a simple page using this HTML from an old ASP.NET Web Forms that look like the following:

How do i get text content in html?

And here’s the HTML code:

test.htm




  
  
  
  Old ITNota.com HTML File


  
Not this one

N/A

Search This!

N/A

Yes, it’s messy, but this was taken from a real legacy application from the production only obfuscated and simplified.

Now, we want to search the text, and then select the whole row which is marked by tr tag in the HTML.

How do i get text content in html?

So, we’re going to use .closest() with the tag name we want to select (which is tr):

    const searchText = 'Search This!'

    document.addEventListener('DOMContentLoaded', function () {

        const spanTags = document.querySelectorAll('span')

        for (let i=0; i

Now, when we reload the test page, the row with the text will look like so:

How do i get text content in html?

In the next post, we will go over on how to search a string and modify it using regular expression all in JavaScript.

Further Reading

How to Use RegEx to Replace Text in JavaScript
JavaScript innerHTML, innerText, and textContent

What is HTML text content?

The textContent property in HTML is used to set or return the text content of the specified node and all its descendants. This property is very similar to nodeValue property but this property returns the text of all child nodes. Syntax: It is used to set the text of node.

How do I get text from DOM element?

HTML DOM Element textContent.
let text = element. textContent;.
element. textContent = "I have changed!";.
let text = document. getElementById("myList"). textContent;.

How do I get div text?

Use the textContent property to get the text of a div element, e.g. const result = element. textContent . The textContent property will return the text content of the div and its descendants. If the element is empty, an empty string is returned.

What is text content?

Textual content comes in many forms, including. semantically in paragraphs, headings, lists and tables; visually in images, infographics and fliers and. programmatically in alternative text, closed captions and transcriptions.