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:
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.
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