DEV Community

Santiago Salazar Pavajeau
Santiago Salazar Pavajeau

Posted on • Updated on

Traversing DOM nodes in JavaScript

Here, I explore the underlying tree structure of the DOM, with a very simple example.

The DOM is literally a tree data structure of javascript objects as nodes. So HTML elements can be accessed as javascript objects with these properties and methods. A practical example is the following algorithm. When we get the top element in the body of the HTML document, for example:

const root = document.getElementById("root")
Enter fullscreen mode Exit fullscreen mode

Then we can access and traverse the rest of the children nodes with a simple recursion algorithm.

function getByClassName(root, className) {

  let result = []
  result.push(root)
    let traverse = (node) => {
        let nodeCh = node.children


        for(let ch of nodeCh){


            if(ch.className === className){
                result.push(ch)
            }

            if(node.children[0]){ // only call recursion if
              traverse(ch)
            }
        }


    }

  traverse(root)

  return result
}
Enter fullscreen mode Exit fullscreen mode

So the parent nodes which are javascript objects (key-value pairs) contain the .children property that contains all the children, as well as many other properties and methods.

This Tree data structure of nested javascript objects is the basis of DOM manipulation (HTML) and libraries like React use the same tree structure but with components to create the virtual DOM Tree. Of course, there are other complexities, but simply put, when we see HTML elements as nodes of the Tree, we can see how they can be traversed with recursion. Just like any other algorithm that uses nodes, and this is the bottom line of how HTML and javascript work together.

Feel more than welcome to reach out with any ideas/comments at Linkedin or Twitter, or check out my portfolio.

Top comments (0)