RFG
RFG

Reputation: 2902

Select range with Rangy library by word number

I'm testing Rangy library as a way to highlight text. It's seems easy to select and highlight text. But, I'm facing the following case:

Say there is a text (HTLM page) and a given range of words position (10 to 23, for example). Is there a way to create this range of words with numbers in Rangy, in order to highlight it?

Thank you.

Update

Here is an example of HTML content:

<div id = "content">
   <h3>World human population</h3>
   <div class="aright w300 shadow">
     <a href="img308.jpg" " title='Population growth.'" >
       <img id_image="308" src="img308.jpg" /></a>
       <div class="iphoto">Population growth.</div>
   </div>
   <p>The world's population is estimated to be 7.646 billion.</p>

   <h3>The development of agriculture and manufacturing</h3>

   <ul class="bullets color">
     <li>
       <p> <strong>Predicted growth.</strong> Population growth increased significantly as the Industrial Revolution gathered pace from 1700 onwards.</p>
     </li>
     <li>
       <p> <strong>Predicted decline.</strong> In the future, the world's population is expected to peak,[17] after which it will decline due to economic reasons, health concerns, land exhaustion and environmental hazards.</p>
     </li>
   </ul>
</div>

How to create a range to selected word between 'estimated' (word 10) and 'growth' (word 24)?

Upvotes: 0

Views: 424

Answers (1)

Dave
Dave

Reputation: 1

You will want to use the findText method with a regex to match the correct words. Pseudo code for the Rangy code without regex:

var searchResultApplier = rangy.createClassApplier("classToApply");
var range = rangy.createRange();
var searchScopeRange = rangy.createRange();
searchScopeRange.selectNodeContents(document.querySelector('#content');
searchResultApplier.undoToRange(range);

searchTerm = new RegExp('your regex to select the correct range of words');
if (range.findText(searchTerm, options) {
    searchResultApplier.applyToRange(range);  // Apply your class
}

This is taken from the Demo code provided with the Rangy library, this is a good tool to test it out.

Upvotes: 0

Related Questions