<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) {
// Your code can go here - acting on the way down
// the tree towards the branches
for (var i = 0; i < el.childNodes.length; i++) {
traverse(el.childNodes[i], str);
var node = el.childNodes[i].textContent;
if(node){
var string = node.toString();
var i = string.search("text");
if (i > 0){
el.childNodes[i].parentNode.className = "searchHit";
}
}
}
// Or your code can go here - acting on the way back up
// the tree towards the root
}
traverse(document.documentElement, 'text');
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.