Skip to content

Instantly share code, notes, and snippets.

@mlhaufe
Last active December 17, 2015 12:19
Show Gist options
  • Save mlhaufe/5609014 to your computer and use it in GitHub Desktop.
Save mlhaufe/5609014 to your computer and use it in GitHub Desktop.
Highlight text in an html document
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