DEV Community

Ryosuke
Ryosuke

Posted on

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

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?

Top comments (2)

Collapse
 
johnkazer profile image
John Kazer • Edited

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...

Collapse
 
karataev profile image
Eugene Karataev

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);