I can use createElement() to create an HTML element via JavaScript like this:
let div = document.createElement('div');
But how can I add a CSS class to my newly created div?
I tried something like this, but didn't work:
let div = document.createElement('div class=myDiv');
The document. createElement() accepts an HTML tag name and returns a new Node with the Element type.
var div = document. createElement("div"); div. style. width = "100px"; div.
The HTML DOM createElement() method is used for creating an HTML element dynamically using JavaScript. It takes the element name as the parameter and creates that element node. You need to use the appendChild() method to have the newly created element as part of DOM .
Do div.classList.add
let div = document.createElement('div');
div.classList.add('test');
let text = document.createTextNode('Test');
div.appendChild(text);
document.body.appendChild(div)
.test {
color: green;
}
You can also do by className
let div = document.createElement('div');
div.className = 'test';
let text = document.createTextNode('Test');
div.appendChild(text);
document.body.appendChild(div)
.test {
color: red;
}
You can use Element.classList.add
let div = document.createElement('div');
div.classList.add("myDiv")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With