i have 6 div
s with id
wrapperX
(X
is number 1 till 6)
when I want to change its background color with for
loop
error show on the log which says Uncaught TypeError: Cannot read property 'style' of null
when I'm not use template literal it works but I must write the code one by one
// show error
for (let i = 0; i < 6; i++) {
let eleSelect = document.getElementById(`wrapper${i}`);
eleSelect.style.setProperty('background-color', 'green');
console.log(eleSelect);
}
// it works
for (let i = 0; i < 6; i++) {
let eleSelect = document.getElementById('wrapper0');
// i must repeat the code till 5
eleSelect.style.setProperty('background-color', 'green');
console.log(eleSelect);
}
css code (i think it's necessary to include here) :
#wrapper0, #wrapper1, #wrapper2, #wrapper3, #wrapper4, #wrapper5{
width: 100px; height: 100px; background-color: black;
}
html:
<div id="wrapper0"></div><div id="wrapper1"></div><div id="wrapper2"></div><div id="wrapper3"></div><div id="wrapper4"></div><div id="wrapper5"></div>