loading...

What's your preferred method for inserting DOM elements in vanilla JS?

whoisryosuke profile image Ryosuke ・1 min read

From <template> to template literals to the classic createElement(), what technique do you prefer to use when you need to take data, create DOM elements, and insert it into the DOM somewhere?

Discussion

markdown guide
 

Handling complex DOM manipulations with vanillaJS is tough.
For simple cases I use createElement() and fullfill the element with innerHTML:

let title = 'DOM Manipulation';
let description = '🤔';
let el = document.createElement('div');
el.innerHTML = `
<h1>${title}</h1>
<p>${description}</p>
`;
document.body.appendChild(el);
 

I like pug and having started to learn functional programming I have discovered pug-vdom.

So now I build my logic and state then inject it into a pug template and apply the pug-vdom virtual DOM to update the DOM. Not sure if that still counts as vanilla JS though!

I guess is not really about inserting into the DOM either, as all nodes already exist in the template to begin with...