Practice Set, Week 8, DOM Traversal
by subsari
HTML
<h3>Practice Set, Week 8, DOM Traversal</h3>
<p>Code is provided here that will traverse the DOM. Your job is to add some code that will take some action at each node.</p>
<p>Your task is to find every element that has the word "text" in it, and add the className "searchHit" to their parent elements.</p>
<p>The steps to do this will look something like this:</p>
<ol>
<li>At each node, determine if it's a text node</li>
<li>If so, find out if the target string is within the text content of the node.</li>
<li>If so, get the parent node and set its class attribute to "searchHit"</li>
</ol>
<p>If you've got it, each element containing the word 'text' will be highlighted in yellow. </p>
CSS
.searchHit {
background-color:yellow;
}
JavaScript
function traverse(el, str) {
for (var i = 0; i < el.childNodes.length; i++) {
processNodeBusinessRules(el.childNodes[i]); // apply business rules to node
traverse(el.childNodes[i], str); // recursively traverse document tree
}
}
// main function to apply business rules
function processNodeBusinessRules(node){
var isTypeText = nodeTypeIsText(node);
var containsText = nodeContainsText(node, "text");
if (!isTypeText) return;
if (!containsText) return;
// append class because node matches type and contains text
appendToParentNodeClass(node, "searchHit");
}
// utility function to determine node type matches type text
function nodeTypeIsText(node){
return node.nodeType == 3;
}
// utility function to determine node contains text
function nodeContainsText(node, text){
return node.textContent.indexOf(text) > -1;
}
// utility function append to the node's parent class
function appendToParentNodeClass(node, className){
node.parentElement.classList.add(className);
}
traverse(document.documentElement, 'text');