Can someone help me with a javascript function that can highlight text on a web page. And the requirement is to - highlight only once, not like highlight all occurrences of the text as we do in case of search.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
I was wondering that too, you could try what I learned on this post.
I used:
you could also try it here: http://henriquedonati.com/projects/Extension/extension.html
xc
You can use the jquery highlight effect.
But if you are interested in raw javascript code, take a look at what I got Simply copy paste into an HTML, open the file and click "highlight" - this should highlight the word "fox". Performance wise I think this would do for small text and a single repetition (like you specified)
Edits:
Using
replace
I see this answer gained some popularity, I thought I might add on it. You can also easily use replace
"the fox jumped over the fence".replace(/fox/,"<span>fox</span>");
Or for multiple occurrences (not relevant for the question, but was asked in comments) you simply add
global
on the replace regular expression."the fox jumped over the other fox".replace(/fox/g,"<span>fox</span>");
Hope this helps to the intrigued commenters.
Replacing the HTML to the entire web-page
to replace the HTML for an entire web-page, you should refer to
innerHTML
of the document's body.document.body.innerHTML
Simple TypeScript example
NOTE: While I agree with @Stefan in many things, I only needed a simple match highlighting:
And then constructing the actual result:
None of the other solutions really fit my needs, and although Stefan Steiger's solution worked as I expected I found it a bit too verbose.
Following is my attempt:
I would also recommend using something like escape-string-regexp if your keywords can have special characters that would need to be escaped in regexes:
Since HTML5 you can use the
<mark></mark>
tags to highlight text. You can use javascript to wrap some text/keyword between these tags. Here is a little example of how to mark and unmark text.JSFIDDLE DEMO
Using the surroundContents() method on the Range type. Its only argument is an element which will wrap that Range.