4 handy ways to create an element with properties in Javascript

Felippe Regazio - Jun 14 '19 - - Dev Community

Here are some different ways to create an element with some properties using Javascript. You can paste all of them directly in the console. Some are more handy than others, but the purpose of this post is primarily for fun.

The Oldschool

let elem1 = document.createElement('div');
elem1.id = 'fizz';
Enter fullscreen mode Exit fullscreen mode

The Coolest

I learnt this here on dev.to with Sam Thorogood, and im not finding the original post for now (i cant remember where but i know that i read about it on his post). Thanks Sam.

let elem2 = Object.assign(document.createElement('div'), {
  id: 'fizz'
});
Enter fullscreen mode Exit fullscreen mode

The Expensive

I think this can be very useful when you want o create a complex element tree with many children and have sure that is all ok.

let html = '<div id="fizz"></div>';
let elem3 = new DOMParser().parseFromString(html, 'text/html').body.firstChild;
Enter fullscreen mode Exit fullscreen mode

The Ugly

let elem4 = document.createElement('div');
for (var [key, value] of Object.entries({id:'fizz'})) {
  elem4[key] = value;
}
Enter fullscreen mode Exit fullscreen mode

I didnt checked all the concerns with those codes as compatibility etc, but i think its a nice thing to know anyway. Google or friends can surely help about the applicability concerns. If you know some other cool ways, please share :)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player