Skip to content

Instantly share code, notes, and snippets.

@awrowse
Created February 16, 2012 16:00
Show Gist options
  • Save awrowse/1845966 to your computer and use it in GitHub Desktop.
Save awrowse/1845966 to your computer and use it in GitHub Desktop.
JS Dom Walk
/**
* Recursive funciton to walk dom and replace any matched dictionary
* terms with a span tag and special css class
* @param element DOMElement
*/
function _walkElement(element){
//loop over all children of element
var el = element.firstChild;
if(el){
do{
//console.log(el.childNodes.length);
/* Are we at a text node? */
if(el.nodeType === 3){
var oldvalue = el.nodeValue;
var newvalue = oldvalue;
//Do something here
if(newvalue !== oldvalue){
/* Element only contained a single text node. */
if(element.childNodes.length == 1){
element.innerHTML = newvalue;
} else {
el.nodeValue = newvalue;
}
}
/* we have children. lets get recursive */
} else {
/* Recursion GO! */
_walkElement(el);
}
/* Fix for IE. It pukes if you call nextSibling on a text node with no next sibling */
try{ var testel = el.nextSibling; }catch(ex){ break; }
/* Let's process the next sibling */
}while(el = el.nextSibling);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment