conk conk - 1 year ago 120
HTML Question

JavaScript DOM parsing

So, I got this question in an exam paper and never really figured out how to do it.

I'm aware of how to do basic traversing through a DOM tree but this seemed a bit out of my scope.

Any help would be appreciated.

Create a JavaScript function which,when called, turns the background color of all text in
elements of the HTML page to blue. However, you cannot use
here(or any other built in function which finds elements by their names)... instead, you need to traverse the DOM tree element by element. Remember that elements might be nested within other elements.

also jQuery is not allowed...
Just to clarify....My problem is I dont know how to write the function to traverse the tree and change background color etc.

Answer Source

You can use this very simple function:

function changeBackgroundColor() {
  // predefine our element variable
  var element,
    // get all the nodes in the document
    nodes = document.createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT);
  // loop through the nodes
  while(element = nodes.nextNode()) {
    // check if the current node is a "<br />" or "<div />" element
    if(element.tagName == "BR" || element.tagName == "DIV") {
      // change the background color of the current element = "blue";

Call the function like this:


Here is some simple HTML that you can test the function on:

<!DOCTYPE html>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <title>JS DOM Question</title>
  <div>Hello World!</div>
  <p>Good day World</p>
  <span>Good evening World!</span>
  <i>Good night World!</i>
  <div>Good morning World!</div>

NOTE: the <br /> element is used to break lines, your not actually supposed to store content in it.

Good luck and all the best.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download