Converting a DOM Object to Real DOM Elements in JavaScript

In many frontend interviews, you may be asked to convert a virtual DOM object into actual DOM elements. This exercise tests your understanding of the Document Object Model (DOM) and your ability to manipulate it dynamically. In this article, we will explore how to transform a virtual DOM object into real DOM elements using vanilla JavaScript. This approach is not only a common interview question but also a valuable technique for building dynamic user interfaces.

Understanding the Virtual DOM Object that you will be given:

const dom = {
  type: 'div',
  props: { id: 'channel' },
  children: [
    { type: 'h1', children: ['Hey Rowdy Coders!'] }
  ]
};

Here’s a breakdown of the structure:

  • type: Represents the HTML tag (e.g., div, h1).
  • props: An object containing attributes for the element. In this example, we have an id attribute.
  • children: An array that can contain strings (representing text nodes) or more virtual DOM objects.

We need to convert this DOM object to DOM Element.

Step-by-Step Approach to Convert the Virtual DOM Object

1. Create a Recursive Function

We need to write a function that:

  • Creates an element based on the type.
  • Sets attributes from the props object.
  • Recursively processes the children array, creating text nodes for strings and calling itself for nested elements.

2. Append the Created Element to the Document

After creating the DOM element, you can append it to a specific container in your document.

function createDOMElement(node) {
  // If the node is a string, return a text node.
  if (typeof node === 'string') {
    return document.createTextNode(node);
  }

  // Create the element based on the node's type.
  const element = document.createElement(node.type);

  // Set the attributes (props) on the element.
  if (node.props) {
    for (const [key, value] of Object.entries(node.props)) {
      element.setAttribute(key, value);
    }
  }

  // Process each child and append it to the current element.
  if (node.children && Array.isArray(node.children)) {
    node.children.forEach(child => {
      element.appendChild(createDOMElement(child));
    });
  }

  return element;
}

// Example usage:
const dom = {
  type: 'div',
  props: { id: 'channel' },
  children: [
    { type: 'h1', children: ['Hey Rowdy Coders!'] }
  ]
};

const realDOMElement = createDOMElement(dom);
document.body.appendChild(realDOMElement);

Explanation

  1. Handling Text Nodes:
    • If the node is a string, createDOMElement creates and returns a text node using document.createTextNode(node).
  2. Element Creation:
    • For a virtual DOM object, document.createElement(node.type) creates the actual element (e.g., a <div> for type: 'div').
  3. Setting Attributes:
    • The function iterates over node.props using Object.entries and applies each attribute to the element with element.setAttribute(key, value).
  4. Processing Children:
    • If node.children exists and is an array, the function processes each child recursively.
    • This means that if a child is another virtual DOM object, createDOMElement will create that element and append it to the parent, building the full DOM tree.
  5. Appending to the Document:
    • Finally, we append the created DOM element to the document using document.body.appendChild(realDOMElement), making it visible on the page.

Once you load this in the HTML file, you will be seeing the page something like below.

Converting a DOM Object to Real DOM Elements in JavaScript

Understanding how to convert a virtual DOM object into real DOM elements is a powerful skill that demonstrates your mastery of JavaScript and DOM manipulation. This question was asked in many interviews including FAANG companies.

Stay tuned!