How to highlight all text occurrences in a HTML page with JavaScript?

后端 未结 4 1497
逝去的感伤
逝去的感伤 2020-12-09 09:40

I really thought this would have been answered years ago, still I did not find any solution:

I want to highlight (i.e. make a colored background) all occurrences of

4条回答
  •  遥遥无期
    2020-12-09 10:08

    I struggled to find a robust text highlighter that duplicates the browsers ctrl + f functionality for months. I've used a host of jQuery plugins. Some are better than others but none are capable of spanning HTML. Say you want to find text that includes a link - the browser can do it but no jQuery plugins I've found can.

    Turns out bare naked javascript has the answer. Just window.find().

    find(string, matchcase, searchBackward)
    

    string : The text string for which to search.

    matchcase : Boolean value. If true, specifies a case-sensitive search. If you supply this parameter, you must also supply backward.

    searchBackward : Boolean. If true, specifies a backward search. If you supply this parameter, you must also supply casesensitive.

    It highlights html laden strings and it's compatible with every browser you care about. Read more about it at http://www.w3resource.com/javascript/client-object-property-method/window-find.php

    The unfortunate thing is you can't seem to do anything with it. I can't wrap it in styled span tags, get the position, scroll to it or change the highlight colour. I'm still looking for the ideal ctrl + f JS function.

提交回复
热议问题