Question

Write a simple JavaScript program that will recursively walk the DOM for an associated HTML file ...

write a simple JavaScript program that will recursively walk the DOM for an associated HTML file and print the types of the elements encountered (embedded data need not be printed, we are just interested in the structure), each preceded by an integer reflecting the element’s nesting level within the hierarchical structure of the HTML document. Thus,<HEAD>and <BODY> would be at the second level (‘2’) while <HTML>, would naturally be at the first level (‘1’). You should also print the closing tags for each element found to make the nesting clear. Thus, your output should look something like the following:

1 <HTML>

2<HEAD>

  element types in “<HEAD></HEAD>” labelled appropriately

2 </HEAD>

2<BODY>

    element types in “<BODY></BODY>” labelled appropriately

2</BODY>

1</HTML>

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Let's say this following is our html code..

<!doctype html>
       <HTML>
       <HEAD>
       </HEAD>
       <BODY>
           <P> Top 3 Channel 3 Thai actresses: </P>
           <ol>
           <li>U</li>
           <li>V</li>
           <li>B</li>
           </ol> 
         <div id="idDiv"></div>
         <script type="text/javascript" 
          src="script.js"> 
         </script>
      <BODY>
      </HTML>

JavaScript code:

var element = document.getElementById("idDiv");

function printNodeInfo(node) {
  if (node.nodeType == Node.TEXT_NODE && !node.nodeValue.trim()) {
    return;
  }
  element.innerHTML += node;
  element.innerHTML += ", nodeName: " + node.nodeName;
  element.innerHTML += ", nodeType: " + node.nodeType;
  element.innerHTML += ", innerHTML: " + node.innerHTML;
  element.innerHTML += "<br>";
}

// Get a handle of the ordered-list node.
var orderedlistNode = document.getElementsByTagName("ol")[0];
theDOMElementWalker(orderedlistNode);

function theDOMElementWalker(node) {
  if (node.nodeType == 1) {
    node = node.firstChild;

    while (node) {
      theDOMElementWalker(node);
      printNodeInfo(node);
      node = node.nextSibling;
    }
  }
}
element.innerHTML += "<br>";
Add a comment
Know the answer?
Add Answer to:
Write a simple JavaScript program that will recursively walk the DOM for an associated HTML file ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT