Sometimes, we want to use querySelector to find element by inner text with JavaScript.
In this article, we’ll look at how to use querySelector to find element by inner text with JavaScript.
How to use querySelector to find element by inner text with JavaScript?
To use querySelector to find element by inner text with JavaScript, we can use the document.evaluate
method.
For instance, we write
const headings = document.evaluate(
"//h1[contains(., 'Hello')]",
document,
null,
XPathResult.ANY_TYPE,
null
);
const thisHeading = headings.iterateNext();
to call document.evaluate
with the xpath that has the inner text we’re looking for in an element.
document
is set as the 2nd argument so we look for the element in the whole document.
Then we get the first element that has the given xpath with iterateNext
.
Conclusion
To use querySelector to find element by inner text with JavaScript, we can use the document.evaluate
method.