DEV Community

Felippe Regazio
Felippe Regazio

Posted on

4 handy ways to create an element with properties in Javascript

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

Top comments (2)

Collapse
 
wiltel492019 profile image
Wiltel492019

I got 7 on it. Great start keep working on it... don't stop until you successful in or at JavaScript and Other CPL's out there today.
Wiltel49@gmail.com
AAS ITI MICHIGAN

Collapse
 
kevinhch profile image
Kevin

The classic 2:
const classicTwo = document.createElement('div')
classicTwo.setAttribute('id','fizz')
And now u can add this element to a parent element