Create an element with ID attribute using JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Create an element with ID attribute using JS #

To create an element with an id attribute:

  1. Use the document.createElement() method to create the element.
  2. Use the setAttribute() method to set the id attribute on the element.
  3. Add the element to the page using the appendChild() method.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <style> #my-id { background-color: tomato; color: aliceblue; width: 150px; height: 150px; } </style> <body> <div id="box"></div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
// ✅ Create element const el = document.createElement('div'); // ✅ Set ID attribute on element el.setAttribute('id', 'my-id'); // ✅ Add text content to element el.textContent = 'Hello world'; // ✅ Or set the innerHTML of the element // el.innerHTML = `<span>Hello world</span>`; // ✅ add element to DOM const box = document.getElementById('box'); box.appendChild(el);

We used the document.createElement method to create the element.

The only parameter we passed to the method is the type of element to be created (div in the example).

The createElement method returns the newly created element.

We used the setAttribute method to set the id attribute on the element.

The setAttribute method takes 2 parameters:

  1. name - the name of the attribute whose value is to be set.
  2. value - the value to assign to the attribute.

In the example, we set the value of the element's id attribute to my-id.

If the attribute already exists, the value is updated, otherwise a new attribute is added with the specified name and value.

You can use the textContent property to set the element's text content or the innerHTML property to set the element's inner HTML markup.

You shouldn't use the innerHTML property with user provided data without escaping it. This would leave your application open to cross-site scripting attacks.

You can use the appendChild method to add the element to the page.

The method adds a node to the end of the list of children of the element it was called on.

If I load the page from the example, I can see that the id attribute has been set on the newly created element.

id set successfully

And the page shows that the styles from the style tag that are scoped to the specified id have been applied.

id styles applied successfully

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.