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
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Old ITNota.com HTML File</title> </head> <body> <table> <tr> <td class="adminaxsSD1" width="30%"> <span id="DltUserService_Label1_1">Not this one</span> </td> <td class="adminaxsSD1" align="center"> <table> <tr> <td> <select name="DltUserService$ctl03$ddlUserAccess" id="DltUserService_ddlUserAccess_1" disabled="disabled" class="aspNetDisabled"> <option value="N">No Access</option> <option selected="selected" value="F">All Options</option> <option value="L">Selected Accounts</option> </select> </td> </tr> </table> </td> <td align="left" width="70%"> <div id="DltUserService_panelCtl_1"> <p>N/A</p> </div> </td> </tr> <tr> <td class="adminaxsSD1" width="30%"> <span id="DltUserService_Label1_2">Search This!</span> </td> <td class="adminaxsSD1" align="center"> <table> <tr> <td> <select name="DltUserService$ctl03$ddlUserAccess" id="DltUserService_ddlUserAccess_2" disabled="disabled" class="aspNetDisabled"> <option value="N">No Access</option> <option selected="selected" value="F">All Options</option> <option value="L">Selected Accounts</option> </select> </td> </tr> </table> </td> <td align="left" width="70%"> <div id="DltUserService_panelCtl_2"> <p>N/A</p> </div> </td> </tr> </table> </body> </html>
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<spanTags.length; i++) { if (spanTags[i].textContent == searchText) { const elementId = spanTags[i].id // Change background to maroon document.getElementById(elementId) .closest('tr') .style.background = 'maroon' } } })
Now, when we reload the test page, the row with the text will look like so:
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