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.
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.
The search() method executes a search for a match between a regular expression and this String object.
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.
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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With