Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.createElement('div') with a class [duplicate]

Tags:

javascript

css

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');
like image 677
user1941537 Avatar asked Mar 18 '19 15:03

user1941537


People also ask

What does document createElement (' a ') return?

The document. createElement() accepts an HTML tag name and returns a new Node with the Element type.

How do I create a div in createElement?

var div = document. createElement("div"); div. style. width = "100px"; div.

What is the purpose of HTML DOM createElement () method?

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 .


2 Answers

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;
}
like image 139
brk Avatar answered Oct 22 '22 18:10

brk


You can use Element.classList.add

let div = document.createElement('div');
div.classList.add("myDiv")
like image 36
R3tep Avatar answered Oct 22 '22 17:10

R3tep