Document.createElement('div') With A Class
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 tri
Solution 1:
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;
}
Solution 2:
You can use Element.classList.add
let div = document.createElement('div');
div.classList.add("myDiv")
Post a Comment for "Document.createElement('div') With A Class"