Utilizing the
[...document.querySelectorAll("*")]
technique involves extracting the
nodeValue
from
each and every element.
This process places the burden on the (slower) JavaScript Engine to handle.
Alternatively, you can leverage the TreeWalker API to specifically target TextNodes
.
Here, the responsibility shifts to the (faster) Browser Engine.
IE9 was the final browser to integrate the TreeWalker API, making this approach available for over a decade now...
(despite this, some individuals still opt for the more sluggish jQuery contains or similar methods)
TreeWalker API
#Text
Nodes possess nodeType 4
and keep in mind that whitespace characters (space, return, tab) separating nodes are considered TextNodes
Note that nodeNames within the HTML NameSpace are UPPERCASE;
while those within SVG NameSpace are lowercase
<body>
<svg something>
<g id=somethingelse>
<text id=ONE>something</text>
<text id=TWO>nothing</text>
</g>
</svg>
</body>
<script>
function findNodes(
str = '',
root = document.body
) {
let tree = document.createTreeWalker(root, 4);
let nodes = [];
let node;
while (node = tree.nextNode()) {
if (node.parentNode.nodeName === "text"
&&
node.data.includes(str)) {
nodes.push(node);
}
}
console.log('Find:', str)
nodes.map((text, idx, arr) => {
console.log(`${idx+1}/${arr.length} `, text.data, ' in:', text.parentNode.id);
});
return nodes;
}
findNodes('something');
findNodes('thing');
</script>