DEV Community

loading...

4 handy ways to create an element with properties in Javascript

Felippe Regazio
web developer - js, [s]css, node, php, python - intp, lifelong learner, father, skateboarder. a strange carbon-based lifeform.
・1 min read

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

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

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;

The Ugly

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

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

Discussion (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