简体   繁体   中英

find all elements containing string in a html

I want to find all elements in my DOM that have a certain string in them, is it possible? I tried to just iterate through all the elements but it took way too much time

So I found out a way to do that:

Here we use XPath to find all those childless elements which aren't scripts:

 var nodes= document.evaluate(".//*[not(self::script) and not(*)]", document, null, XPathResult.ANY_TYPE, null );

Now here we get them into an array so we could iterate through them:

 var elements = [] var nextNode = nodes.iterateNext(); while(nextHeading) { elements.push(nextNode) nextNode = nodes.iterateNext(); }

And finally, we can run through them and check whether they contain the phrase we are looking for:

 var phrase = 'hello world' for(element of elements) { var text = element.innerText if( text && text.includes(phrase)) { console.log(element) } }

----------------------EDIT----------------------

As @Heretic Monkey wisefully noted, I didn't think about a situation in which an element will contain both a text node and another child element

Replacing the first line with the following should do the trick, finding all elements which aren't scripts and contaiting a text node, you could replace the regex inside to already search by a specific term which will also make some of the checks I did earlier irrelevant.

 var nodes= document.evaluate(".//*[not(self::script) and matches(text(),'(\w)','i')]", document, null, XPathResult.ANY_TYPE, null );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM