JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to create an element with classes using JavaScript?

To create an element with classes, follow the below procedure:

  1. Call the document.createElement() method and pass the name of an HTML element you want to create.
  2. To add one or more classes, call the classList.add() method and pass class names
  3. After that, use the textContent or innerHTML property to set the content of the newly created element.
  4. Finally, use the appendChild() method to add an element to the HTML page.

Let's look at an example that shows you how to create an element with classes.

HTML Code

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <style>
      .pd-around{
        padding:10px;
      }
      .large-text{
        font-size:30px;
      }
      .bg-blue{
        background-color: blue
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script src="index.js"></script>
  </body>
</html>

JavaScript Code

index.js
let element = document.createElement('div');
element.classList.add('pd-around', 'large-text', 'bg-blue');
element.textContent = 'Learning JavaScript';

let container = document.getElementById('container');
container.appendChild(element);

Create an element with classes

The document.createElement() method accepts an HTML element and returns that HTML element. In this example, we have passed div to the document.createElement() method and it has returned the newly create div element.

Using the classList.add() method, you add classes to the element. This method accepts more or more class names. The classList.add() method replaces already existing class names with the class names passed to it.

To set the text content, use the textContent property. If you want to set HTML markups as the content of an element, then use the innerHTML property.

After creating an element with classes, you have to add that element to the page. For doing this, you can use the appendChild() method.

Recommended Posts