Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find DOM element containing string matching regular expression [closed]

I need to find on HTML page all text fragments matching specific regular expression (that is, I need to ignore tags so that '< span>First name: < /span>< br/>< b>John< /b>' will match 'First name: John'), and than highlight these found fragments (by decorating with new elements and applying custom css styles) and be able to locate these fragments, e.g. be able to scroll these into view. Functionality is similar to what Skype browser plugin is doing with phone numbers found on page.

like image 771
Igor Romanov Avatar asked Oct 12 '11 21:10

Igor Romanov


People also ask

How do I find my DOM element?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

What does Search () do in JavaScript?

The search() method executes a search for a match between a regular expression and this String object.

How do I get an element from innerHTML?

How it works. First, get the <ul> element with the id menu using the getElementById() method. Second, create a new <li> element and add it to the <ul> element using the createElement() and appendChild() methods. Third, get the HTML of the <ul> element using the innerHTML property of the <ul> element.


2 Answers

You can either recursively walk down the DOM looking at the textContent or innerText property (as appropriate) of elements, or you can use loop over the collection returned by getElementsByTagName. Either way, once you have identified the text and the parent element, you need to work out how to replace it.

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

like image 114
RobG Avatar answered Oct 31 '22 07:10

RobG


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

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

Here is a running example: http://jsfiddle.net/XzwNj/

like image 34
etuardu Avatar answered Oct 31 '22 08:10

etuardu