简体   繁体   中英

Match all occurrences with window.find()

For example if I have a web page HTML like below

<body>
        Hello Techies, <br>
        Techies here.
</body>  

If I search for "Techies" using

 var sel = window.getSelection(); 
 sel.collapse(document.body, 0); 
 document.body.offsetHeight;
 if (window.find("Techies", true)) { 
   document.execCommand("hiliteColor", false, "YellowGreen"); 
   sel.collapseToEnd(); 
 }

It is Highlighting only the first occurred of the "Techies". But when I search with Ctrl+F the first occurrence will be highlighted in Dark and next occurrences will be highlighted in light color mode. How can I achieve the same with the above code.

Try using a while loop:

if (window.find("Techies", true)) { 
   document.execCommand("hiliteColor", false, "FirstColor");
   while (window.find("Techies", true)) {
      document.execCommand("hiliteColor", false, "SecondColor");
   }
   ...
}

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