Subscribe

JavaScript creating a new element

โœ๏ธ

How to create a new element in JavaScript

21 Apr, 2021 ยท 2 min read

I've realized I've done quite a few articles already where I used the technique to create elements from scratch in Vanilla JavaScript.

But I've never actually gone through the basics of creating elements in JavaScript.

TLDR; You can use document.createElement() to create new elements.

Creating new elements in JavaScript

When using the createElement() function you can pass the element you can to create, but you don't need to pass in the brackets <>.

Some examples:

document.createElement('div');
document.createElement('aside');
document.createElement('custom');

Run this in JavaScript and it will create these three elements for you.

As you can see it allows known HTML element or even custom elements.

These however will not get added to the dom directly. We can console log them to see what's happening.

Created element in JavaScript

Let's create a full element and add it to the dom now.

let div = document.createElement('div');
div.textContent = `I'm created`;
div.style.backgroundColor = 'red';
div.id = 'custom_id';

document.body.appendChild(div);

And this will actually append a red div to our dom. The red div will have a custom ID even.

Styled element to dom in JavaScript

Pretty cool right? You can try this out yourself in the following Codepen.

See the Pen JavaScript creating a new element by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API

Join 1828 devs and subscribe to my newsletter