Problem:
I have a JS function and I’m trying to pass multiple variables to a document.querySelectorAll
.
It’s working but only returns the first one.
I’m calling the function like this :
<body onload ="format_selectboxes('custom-select_1','custom-select_2','custom-select_3')" >
Here is the function :
function format_selectboxes(c1,c2,c3) {
var x;
x = document.querySelectorAll("."+c1,"."+c2,"."+c3);
//alert(x)
l = x.length;
// alert(l)
for (i = 0; i < l; i++) {
// do stuff here
}
How do I get the 3 working please ?
Thank you
Solution:
You’re creating the selector wrong, the ,
does not work when appending string like that.
Currently you have:
const c1 = 'foo',
c2 = 'bar',
c3 = 'foobar';
const test = ("."+c1,"."+c2,"."+c3);
console.log(test);
Which logs .foobar
, not the string you’re expecting.
So when we alter that string concatenation to the format .A, .B, .C
well see the correct value .foo, .bar, .foobar
:
const c1 = 'foo',
c2 = 'bar',
c3 = 'foobar';
const test = (`.${c1}, .${c2}, .${c3}`);
console.log(test);