JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

JavaScript

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

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

  const result = document.createElement(ele.type);
	
  if(ele.props === 'object') {
  	for(let [key, val] of Object.entries(ele.props)) {
    	result.setAttribute(key, val);
    }
  }
  
  if(Array.isArray(ele.children)) {
  	ele.children.forEach((child) => {
    	const childDiv = createDOMElement(child);
      result.appendChild(childDiv);
    })
  } else if (typeof ele.children === 'string') {
  	result.appendChild(document.createTextNode(ele.children));
  }
  
  return result;
}

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