Create an Element with Classes using JavaScript

avatar

Borislav Hadzhiev

Fri Jan 07 20222 min read

Create an Element with Classes using JavaScript #

To create an element with classes:

  1. Use the document.createElement() method to create the element.
  2. Use the classList.add() method to add one or more classes to 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" /> <style> .bg-yellow { background-color: yellow; } .text-lg { font-size: 2rem; } </style> </head> <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'); // ✅ Add classes to element el.classList.add('bg-yellow', 'text-lg'); // ✅ Add text content to element el.textContent = 'Hello world'; // ✅ Or set the innerHTML of the element // el.innerHTML = `<span>One, two, three</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 classList.add method to add two classes to the element.

The method takes one or more class names as parameters and adds them to the element's class list.

If a class is already present on the element, the add() method omits the class.

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 classes have been applied successfully.

classes applied successfully

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee