DEV Community

ali
ali

Posted on

Traversing a DOM tree

There was a need at work to apply inline styles to each DOM element in a page.This was a rare occasion to actually traverse a tree, an exercise many of us have done, I am sure, to practice for interviews or as part of homework.

My solution was as follows

const app = document.querySelector("#app");

const inlineStyles = (node) => {
  const clone = node.cloneNode();
  const computedStyles = window.getComputedStyle(node);
  Object.keys(computedStyles).forEach((key) => {
    clone.style.setProperty(key, computedStyles.getPropertyValue(key));
  });

  return clone;
}

function traverseDOM(node) {
  if (!node) {
    return;
  }

  const updatedNode = inlineStyles(node);
  for (let child of updatedNode.children) {
    const updatedChild = traverseDOM(child);
    updatedNode.appendChild(updatedChild);
  }

  return updatedNode;
}
Enter fullscreen mode Exit fullscreen mode

The operation performed on each node is inlineStyle. It gets the computed styles of a node and applies them as inline styles.

This is a DOM tree so it is not built in a specific order and each node has many children, so it is not a binary seach tree.Were it a binary search tree, then our traversal order would be pre-order; We perform the operation on the root node first and then traverse on the children from increasing index position, i.e. from left most to right most.

Top comments (0)