Last active
December 17, 2015 12:19
-
-
Save mlhaufe/5609014 to your computer and use it in GitHub Desktop.
Highlight text in an html document
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function selected(){ | |
var sel = window.getSelection(), | |
cnt = sel.rangeCount, | |
ranges=[]; | |
for(var i = 0; i < sel.rangeCount; i++) | |
ranges[i] = sel.getRangeAt(i); | |
return ranges | |
} | |
function highlight(node,sels){ | |
var html = node.innerHTML; | |
sels.forEach(function(sel){ | |
html = html.replace(new RegExp(sel,"g"),"<span class='highlight'>$&</span>") | |
}) | |
node.innerHTML = html | |
} | |
highlight(document.getElementById("foo"),selected()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment