Home > Back-end >  HTML element name issue in JS for-loop
HTML element name issue in JS for-loop

Time:08-19

I have some HTML <p> elements with ids id="hex-1", id="hex-2", etc.

Instead of manipulating them one by one (as follows) in my script file, I'm trying to use a for-loop.

/* Code I'm trying to put in For-loop */ 
document.getElementById("hex-1").innerText = data.colors[0].hex.value
document.getElementById("hex-2").innerText = data.colors[1].hex.value
document.getElementById("hex-3").innerText = data.colors[2].hex.value
document.getElementById("hex-4").innerText = data.colors[3].hex.value
document.getElementById("hex-5").innerText = data.colors[4].hex.value

I've tried like as follows, but it's not working;

/* Try 1 */
for(let i=0; i<data.length; i  ) {
  let hexCode = `hex-${1 i}`
  
  document.getElementById(hexCode).innerText = data.colors[i].hex.value
}

/* Try 2 */
for(let i=0; i<data.length; i  ) {
  let hexCode = "hex-"   (i 1)
  
  document.getElementById(hexCode).innerText = data.colors[i].hex.value
}

CodePudding user response:

As David Thomas mentioned in comments too, It seems you should do something like:

for(let i=0; i < data.colors.length; i  ) {
  let hexCode = `hex-${1 i}`
  document.getElementById(hexCode).innerText = data.colors[i].hex.value
}
  • Related