I want to reduce my javascript code. I have:
let c = document.querySelectorAll(".check"),
l = document.querySelectorAll(".label");
I want to have, for example:
let [c, l] = document.querySelectorAll([".check", ".label"])`
One line. Is it possible?
let [c, l] = document.querySelectorAll([".check", ".label"])
let [c, l] = document.querySelectorAll(".check, .label")
let [c, l] = document.getElementsByClassName([".check", ".label"])
let [c, l] = document.getElementsByClassName(".check, .label")
I want to reduce my javascript code. I have:
let c = document.querySelectorAll(".check"),
l = document.querySelectorAll(".label");
I want to have, for example:
let [c, l] = document.querySelectorAll([".check", ".label"])`
One line. Is it possible?
let [c, l] = document.querySelectorAll([".check", ".label"])
let [c, l] = document.querySelectorAll(".check, .label")
let [c, l] = document.getElementsByClassName([".check", ".label"])
let [c, l] = document.getElementsByClassName(".check, .label")
Technically it is possible:
let [c, l] = [".check", ".label"].map(s => document.querySelectorAll(s));
// or
let [c, l] = ["check", "label"].map(s => document.getElementsByClassName(s));
This approach can come in handy if you have many variables to define. However, for two-three variables that code is possibly less readable than your original one:
let c = document.querySelectorAll(".check"),
l = document.querySelectorAll(".label");
The readability point is out of this question scope.
[one, two] =
will only get the first two elements, and classes might return an arbitrary number of elements. What you might do eventually is create a helper function like:const els = (sel, par = document) => par.querySelectorAll(sel);
and use like:const [c, l] = [els(".check"), els(".label")];
– Roko C. Buljan Commented Feb 4 at 10:45.check
and.label
elements, and they were in the DOM in that order as you're effectively accessing the return values by index. That being said, the code would not be robust in the slightest, which is why this is really not a good idea. – Rory McCrossan Commented Feb 4 at 10:46querySelectorAll
andgetElementsByClassName
(ie static vs live collection). Second, neither of them acceps an array as parameter, but only strings. And even if".check, .label"
is allowed as selector, the elements will be returned in the order they appear in the document, so[c, l] = ...
will only work in one very special situation, ie when there is exactly one.check
and one.label
element in the document, and they appear in the correct order – derpirscher Commented Feb 4 at 10:56