'How do I use variable in a query selector - js?
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)}`;
}
Solution 1:[1]
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}`;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pilchard |
