Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

getElementById doesn't accept template literal

i have 6 divs 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 say 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div id="wrapper0"></div><div id="wrapper1"></div><div id="wrapper2"></div><div id="wrapper3"></div><div id="wrapper4"></div><div id="wrapper5"></div>

>Solution :

Your code does not have a wrapper0 element but your loop counter is set to 0

solution:

for (let i = 1; i <= 6; i++) { 
  let eleSelect = document.getElementById(`wrapper${i}`);
  tempEleSelect.style.setProperty('background-color', 'green');
  console.log(tempEleSelect);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading