sae67
sae67

Reputation: 11

How to use destructirng assignment combined with looking up elements on the page?

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")

Upvotes: -2

Views: 46

Answers (1)

Dzmitry Dranitski
Dzmitry Dranitski

Reputation: 669

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.

Upvotes: 3

Related Questions