Practice Set, Week 8, DOM Traversal

for CSCI E3, Harvard University author(s): Larry Bouthillier

by DustyWhite

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>
<p>text</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);
  }
  // Or your code can go here - acting on the way back up 
  //  the tree towards the root

  // 1) Is it a text node?
  if (el.childNodes.nodeType != Node.TEXT_NODE) {
    console.log("nodeType is " + el.nodeType)
  } else {
    console.log("Yes! This is a text node. I have a place to begin")
  }


  // 2) If so, does it have the word (string) "text" in it?
  var x = document.getElementsByTagName("P").length;
  console.log("There are this many 'Paragraph' elements: " + x);

  // I can't get "includes to work:
  // el.includes("text")

  if (el.childNodes.nodeValue == "text") {
    console.log("Holy crap! This works!")
  } else {
    console.log("Nothing to see here")
  }

  if (el.childNodes.nodeValue == 3) {
    console.log("Holy crap! This works!")
  } else {
    console.log(" . . . no")
  }



  // 3 ) If so, go up one level and assign THAT "element" a class of "searchHit".



}

traverse(document.documentElement, 'text');