Explain Codes LogoExplain Codes Logo

How to get element by innerText

javascript
xpath
node-lists
javascript-queries
Anton ShumikhinbyAnton Shumikhin·Feb 18, 2025
TLDR

Quickly fetch an element by its innerText using XPath in JavaScript:

function getElementByText(text) { const xpath = `//node()[normalize-space(text())='${text.trim()}']`; // Presto! A wild XPath appears. Berry used. It's super effective! return document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; } const myElement = getElementByText("Exact Text"); console.log(myElement); // Abracadabra! Your element magically appears!

Swap "Exact Text" with the text you're hunting. This function sleuths out a matching node in the entire document using XPath like a bloodhound on a mission.

A dive into the rabbit hole: Understanding XPath and textContent

Getting precise with XPath

JavaScript's XPath mode is a heat-seeking missile when it comes to finding elements with text outputs matching up perfectly. But as with all magic tricks, there is always a catch: textContent sniffs out all text nodes, including those playing hide-and-seek, while innerText is deceived by CSS invisibility cloaks. Favor the vigilant textContent when hidden styled text is part of the game.

Treating Node collections like grand Hercules feasts

Whenever we're dealing with a horn of plenty— say paragraphs in an article— getElementsByTagName and querySelectorAll prove to be truer friends. They gift us collections ideal for iteration, so go grab a plate and start feasting:

const textToFind = "Search Query"; let matchingElements = []; // 'Feasting commenced' bell rings document.querySelectorAll('p').forEach(p => { if (p.textContent.includes(textToFind)) { // Nom nom, good piece found matchingElements.push(p); } }); // Log 'meal registers' console.log(matchingElements);

"Remember jQuery? Pepperidge Farm remembers"

In the glorious days of jQuery, the mystical :contains() selector made text searches superbly nifty:

const myElement = $("*:contains('Exact Text')")[0]; console.log(myElement); // Bam! jQuery enters and makes grand ol' memories!

Bear in mind that :contains() has the sword of Gryffindor— it's loyal to the case. For best results, clever text encapsulation is required.

Case files: Navigating edge scenarios

Case 1: Text normalization "Sleek, says the sleek walker"

For exact text searches, remember to normalize space and line breaks to avoid missing potential leads due to formatting quirks. That's "sleek walking" per Moriarty.

let searchText = " My Text "; searchText = searchText.trim().replace(/\s+/g, ' '); // Ooh, so sleek!

Case 2: Passport for older browsers

Legacy browsers do pose a challenge, so consider an interpreter for their linguistic needs – transpilers like Babel may just save the day here since document.evaluate() and the like might speak in strange tongues they don't understand.

Case 3: Your custom time-turner

Crafting your own custom function like getElementsByText can change the game as it streamlines your searches with tags and classList criteria. You also get a time-turner of elements that can be paused once the chosen one is found:

function getElementsByText(text, tag = '*') { let foundElements = []; for (let el of document.getElementsByTagName(tag)) { if (el.textContent.trim() === text) { foundElements.push(el); } } return foundElements; // The prophecy is fulfilled! }

Case 4: The grand feast finale: Spreading NodeLists

Modern JavaScript gives us the spell to transform a NodeList into an array for easy handling. Here, we filter elements with the caveat of using the spread operator:

const allParagraphs = [...document.querySelectorAll('p')]; const slightlyOddMatchingParagraphs = allParagraphs.filter(p => p.textContent.includes('This pudding is enchanted.'));