Sometimes, we want to select an HTML element by their textContent
value with JavaScript.
In this article, we’ll look at how to select an HTML element by their textContent
value with JavaScript.
Select Elements with document.querySelectorAll and Loop Through Them to Find the Ones We Want
We can select multiple elements with document.querySelectorAll
.
Then we can loop through them to find the ones we want with the for-of loop.
For instance, if we have the following HTML:
<div>
foo
</div>
<div>
bar
</div>
<div>
baz
</div>
Then we can the div with text ‘bar’ by writing:
const divs = document.querySelectorAll("div");
const searchText = "bar";
for (const div of divs) {
if (div.textContent.includes(searchText)) {
console.log(div.textContent)
}
}
We select all the divs with document.querySelectorAll
.
Then we loop through each item with the for-of loop.
In the loop body, we check if div.textContent
includes the searchText
with the includes
method.
If it does, then we log it with console log.
Therefore, we should see the console log log 'bar'
as a result.
Search for an Element with the Given Text Content by XPath
Another way to search for an element with the given text content is to use an XPath.
For instance, if we have the following HTML:
<div>
foo
</div>
<div>
bar
</div>
<div>
baz
Then we can the div with text ‘bar’ by writing:
const xpath = "//div[contains(text(),'bar')]";
const matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
console.log(matchingElement)
using the xpath
string.
xpath
is a string that specifies we match the div elements that contains the text ‘bar’.
Then we can use the xpath
string to search for the element we want by calling the document.evaluate
method with the xpath
as the first argument.
document
is the 2nd argument which means we’re search the whole document for the element.
singleNodeValue
returns the first element node that matches the XPath we’re using to search.
Therefore, matchingElement
should be the div element with text content ‘bar’.
Conclusion
We can search for an element with the given text content by selecting elements and looping through them to find it.
Or we can search for it with an XPath.