I have an extremely simple script
which is supposed to grab every element with and id="d"
, then iterate through each of those elements; grabbing the value of their data-color
.
Each time it loops through, it is supposed to change the background of the document
to those values, then alert the value.
It would work, and grab all of the values, and output them; one after the other. However, due to the alerts being too quick for the page to actually change the background
color, I had to put the alerts within a setTimeout
so that the document
could change color, wait 250 milliseconds, THEN alert the value. When I did this though, it would only ever get the last elements data-color
value and alert it.
This is my JavaScript:
var selector = document.querySelectorAll("#d");
for(var i = 0; i < selector.length; i++){
var did = selector[i].getAttribute("data-color");
document.body.style.background = did; // set background to data-color value
setTimeout(function(){ // wait 250 milliseconds (this is where it breaks)
alert(did); // THEN alert the value of data-color
}, 250);
}
And the HTML:
<div data-color="green" id="d"></div>
<div data-color="blue" id="d"></div>
<div data-color="red" id="d"></div>
Why does this happen? Thanks.