JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

JavaScript

function createDOMElement(dom) {
  if (!dom || typeof dom !== 'object') {
    return null;
  }

  const element = document.createElement(dom.type);

  if (dom.props) {
    for (const [key, value] of Object.entries(dom.props)) {
      element.setAttribute(key, value);
    }
  }

  if (Array.isArray(dom.children)) {
    dom.children.forEach((child) => {
      const childElement = createDOMElement(child);
      if (childElement) {
        element.appendChild(childElement);
      }
    });
  } else if (typeof dom.children === 'string') {
    element.appendChild(document.createTextNode(dom.children));
  }

  return element;
}

// Example usage:
const dom = {
  type: 'div',
  props: { id: 'hello' },
  children: [
    { type: 'h1', children: 'HELLO' },
    { type: 'p', props: { class: 'description' }, children: 'This is a description.' },
  ],
};

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