Find a DOM element containing string matching regular expression

I need to find all the text fragments on the HTML page that match a specific regular expression (i.e. I need to ignore the tags so that '< span>First name: < /span>< br/>< b>John< /b>' corresponded to 'First name: John' ), but did not highlight found fragments (by decorating with new elements and applying custom CSS styles) and the ability to find these fragments, for example, be able to scroll through them in the form. The functionality is similar to what the Skype browser plugin does with the phone numbers found on the page.

+6
source share
3 answers

You can either go down the DOM recursively by looking at the textContent or innerText property (if necessary), or you can use a loop over the collection returned by getElementsByTagName. In any case, once you have defined the text and the parent element, you need to figure out how to replace it.

What are your requirements for the structure of the document in the replacement if the string is split into one or more othere elements?

+2
source

You can use jQuery selectors to get the <b> tags containing John that appear after the <span> tag that contains First name: and then, for example, apply a style:

 $("span:contains('First name:') ~ b:contains('John')").css('color','red'); 

Here is an example: http://jsfiddle.net/XzwNj/

+2
source

Have you tried something like this?

document.body.innerHTML.replace(/<\/?[^>]+>/g, '')

-1
source

Source: https://habr.com/ru/post/899171/


All Articles