Walk the DOM and className search
no JQuery, and no getElementByClass
by Elijah Tate
HTML
<div class="mainParent">
<div class="firstLevel">
<div class="firstLevelTitle">
Hello from the First Level
</div>
<div class="firstLevelBody">
<div class="firstLeveContainer">
<div class="anElement">
</div>
<div class="anElement">
</div>
</div>
</div>
</div>
<div class="secondLevel">
<div class="secondLevelTitle">
Hello from the Second Level
</div>
<div class="secondLevelBody">
<div class="secondLevelContainer">
<div class="anElement">
</div>
<div class="anElement">
</div>
</div>
</div>
</div>
</div>
JavaScript
// This function will take in the node that is passed, and systematicaly
// go through all of the rest of the dom below that level.
function walkTheDom(node, funct){
// we pass in a function so that we can do work on the elements we find
funct(node);
// set the node to be the first child of our node
node = node.firstChild;
// recursively run this function so find all of the children that exist
while(node){
walkTheDom(node, funct);
// node will now equal the next sibling of our node so we can look through
// all lower elements
node = node.nextSibling;
}
}
// Here we can search for a className by using walkTheDom
function getElementByClassName(className){
// store the results from our search
var results = [];
// we will always want to scan whole DOM, so we pass in the body
// we pass in "node" into our anon funct. This becomes document.body
// in walktheDom
walkTheDom(document.body, function(node){
var a, c = node.className, i;
// if an element has a className
if(c){
// elements can have more than one className so we
// create an array of these classes by splitting them
// at any white space
a = c.split(' ');
// search our array for the className that we are looking
// for
for(i=0; i < a.length; i++){
// if we find our className then add it to our array and
// break the lop
if(a[i] === className){
results.push(node);
break;
}
}
}
});
return results;
}
var theElements = getElementByClassName("anElement");
console.log("" + theElements.length);
for(var i=0; i<theElements.length; i++){
console.log("My className is: " + theElements[i].className);
theElements[i].className += " someOtherclassName";
}