I am working on a project which has a div with certain children. I want to change first element(s) background color by a variable. For example, if I have 32 children div and variable is 20, the function must be change first 20 divs background color.
I used parent.children
method by this.
My code is like,
function change() {
var parent = document.getElementById("clock");
var child = parent.children;
var howMany = 5;
for (var i=0; i < howMany; i++){
if (child[i].tagName == "DIV") {
child[i].style.backgroundColor = "red";
}
}
}
It works in window.onload
but I must use setTimeout()
in this function. If I use setTimeout()
, I get TypeError: child[i] is undefined
error.
So, what is wrong in my function? Is there a other way to do it?
By the way, I'm pretty much new at Javascript and this is my first question on Stack Overflow.