Skip to content

Instantly share code, notes, and snippets.

@taoufix
Created July 10, 2014 07:58
Show Gist options
  • Save taoufix/3ee6f251d856e9ae957a to your computer and use it in GitHub Desktop.
Save taoufix/3ee6f251d856e9ae957a to your computer and use it in GitHub Desktop.
Highlight keywords
var TEXT="Disponible";
var COLOR = "red";
var BG_COLOR="yellow";
var allText = document.evaluate( "//text()[contains(., '" + TEXT + "' ) or contains(., 'disponible')]", document, null, XPathResult. ORDERED_NODE_SNAPSHOT_TYPE , null);
for(var i=0; i<allText.snapshotLength; i++) {
var cur = allText.snapshotItem(i);
var par = cur.parentNode;
var textInd;
var curName = cur.nodeName;
do {
var curText = cur.nodeValue;
console.log("curText: " + curText);
textInd = curText.indexOf(TEXT);
if(textInd != -1) {
var before = document.createTextNode( curText.substring(0, textInd ) );
var highlight = document. createElement("span");
highlight.class = "highlight";
highlight.textContent = TEXT;
highlight.style.color = COLOR;
highlight.style.backgroundColor = BG_COLOR;
var after = document.createTextNode( curText.substring(textInd + TEXT.length) );
par.insertBefore(before, cur);
par.insertBefore(highlight, cur);
par.insertBefore(after, cur);
par.removeChild(cur);
cur = after;
}
} while(textInd != -1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment