-1

What am I doing wrong? there are 7 pictures with pre-made IDs from "img1" to "img7"

  function changeWidth() {
            let b = 50
            let k = 0
            let l = `"#img${(k + 1)}"`;
            for (let k = 0; k < 7; k++)
                
                document.querySelector("l").width = `${(b = b + 50)}`;

        }

1 Answers1

0

The comment covers the basics; move the template literal inside the loop, remove quotes from inside your template literal, and refer to the variable without quotes.

function changeWidth() {
  let b = 50
  for (let k = 0; k < 7; k++) {
    let l = `#img${(k + 1)}`;
    document.querySelector(l).width = `${(b = b + 50)}`;
  }
}

But you can actually simplify to not use any variables except the index in the loop, start k at 1 instead of 0 to avoid addition, and use getElementById which is more efficient than querySelector.

function changeWidth() {
  for (let k = 1; k <= 7; k++) {
    document.getElementById(`img${k}`).width = `${50 + 50 * k}`;
  }
}
pilchard
  • 12,414
  • 5
  • 11
  • 23