I'm trying to generate some divs dynamically through a for loop. They don't have the color and size styling, even though I've added a class and I can see the class in the developer tools.
public addDivs() {
for(let i = 0; i < 10; i++) {
let div = document.createElement('div');
div.classList.add('test');
div.innerHTML = 'testing'
}
}
.test {
color:red;
background-color:green;
height: 40px;
width: 40px;
}
When I add styling like this it does work.
public addDivs() {
for(let i = 0; i < 10; i++) {
let div = document.createElement('div');
div.innerHTML = 'testing'
div.style.color = 'red';
}
}
Is it possible (without JQuery) to get the styling from a css file?
edit: Also I should add that it started to fail only when I put the code in a for loop.
Append the element after creating it. Existing classes and styles works with dynamically created nodes.
function addDivs() {
for(let i = 0; i < 10; i++) {
let div = document.createElement('div');
div.classList.add('test');
div.innerHTML = 'testing:'+i;
document.querySelector("body").appendChild(div);
}
}
addDivs();
.test {
color:red;
background-color:green;
height: 40px;
width: 100px;
margin-bottom:4px;
}