Render DOM element

JavaScript, Browser, Recursion · Oct 13, 2021

Renders the given DOM tree in the specified DOM element.

  • Destructure the first argument into type and props. Use type to determine if the given element is a text element.
  • Based on the element's type, use either Document.createTextNode() or Document.createElement() to create the DOM element.
  • Use Object.keys() to add attributes to the DOM element and set event listeners, as necessary.
  • Use recursion to render props.children, if any.
  • Finally, use Node.appendChild() to append the DOM element to the specified container.
const renderElement = ({ type, props = {} }, container) => {
  const isTextElement = !type;
  const element = isTextElement
    ? document.createTextNode('')
    : document.createElement(type);

  const isListener = p => p.startsWith('on');
  const isAttribute = p => !isListener(p) && p !== 'children';

  Object.keys(props).forEach(p => {
    if (isAttribute(p)) element[p] = props[p];
    if (!isTextElement && isListener(p))
      element.addEventListener(p.toLowerCase().slice(2), props[p]);
  });

  if (!isTextElement && props.children && props.children.length)
    props.children.forEach(childElement =>
      renderElement(childElement, element)
    );

  container.appendChild(element);
};
const myElement = {
  type: 'button',
  props: {
    type: 'button',
    className: 'btn',
    onClick: () => alert('Clicked'),
    children: [{ props: { nodeValue: 'Click me' } }]
  }
};

renderElement(myElement, document.body);

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • JavaScript DOM Manipulation

    Create, insert, remove and manipulate DOM elements with this collection of JavaScript tips and tricks.

    Collection · 6 snippets

  • Check if HTML element has class

    Checks if the given element has the specified class.

    JavaScript, Browser · Oct 19, 2020

  • Array of element's siblings

    Returns an array containing all the siblings of the given element.

    JavaScript, Browser · Oct 19, 2020

  • Observe element mutations

    Creates a new MutationObserver and runs the provided callback for each mutation on the specified element.

    JavaScript, Browser · Oct 22, 2020