My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Generating Elements With JS

Marco Alka's photo
Marco Alka
·Mar 5, 2018

Say you have that job to create a web app, and what you want to do is generate some HTML elements with JS, based on some JSON response. It's a small app, so you decide against using big-ass frameworks and libraries (and JSX). Now that you actually have to implement the element generation from some kind of template, you find out that there are several ways to actually do that.

You start to wonder: which way is the best one to actually add elements or even element trees to a DOM? What's the most used one and why? How good is the performance of each and what about events, like click, focus, hover, etc., especially on re-render? Do the different ways have specific use-cases? What are advantages and disadvantages?

I consciously do not want to add a poll here, because that would make people click whatever they feel comfortable with instead of giving it a moment to think, re-evaluate the methods and find arguments.

Some methods, which are available using VanillaJS are

  1. document.createElement(); //..., add attributes etc. and append to targetNode
  2. targetNode.innerHTML += '... ${something} ...';, (imagine a template literal here)
  3. targetNode.appendChild(hiddenDiv.cloneNode(true));
  4. targetNode.appendChild(document.importNode(template.content), true);

I will write my view on the above ways into an answer below. What are your thoughts on the topic?