Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
782 views
in Technique[技术] by (71.8m points)

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

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 a (sub-)string on an entire HTML page, completely client-side with JavaScript.

Just as you would use Ctrl+F to search inside Google Chrome: When entering the search term, it highlights all the substrings that match my entered term.

Personally, I would walk all elements of the DOM tree, doing some replace of the search term with something like

<span style="background-color: yellow">MySearchTerm</span>

But I think there must be some more effective way?

My question:

How to use JavaScript (or jQuery) to highlight all substring occurrences inside a HTML page?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...