To create an element with classes, follow the below procedure:
document.createElement()
method and pass the name of an HTML element you want to create.classList.add()
method and pass class namestextContent
or innerHTML
property to set the content of the newly created element.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
<!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
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);
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.