I'm trying to figure out what exactly this piece of code means. But I can't figure out why that spread syntax(...document.querySelectorAll
) is used and what the .map
and the .dataset.filter
does.
const filters = [...document.querySelectorAll('.btn.active')].map(
(el) => el.dataset.filter,
);
CodePudding user response:
The use of spread syntax here is to convert the resulting NodeList from querySelectorAll
into an array so we can use map
. NodeList by itself does not have map
, only forEach
, hence the conversion.
dataset
is a property that contains all of the data-*
attributes - here we are getting data-filter
. See the below snippet for an example.
const filters = [...document.querySelectorAll('.btn.active')]
.map((el) => el.dataset.filter);
console.log(filters); // ["foo", "bar", "baz"]
<div data-filter="foo"></div>
<div data-filter="bar"></div>
<div data-filter="baz"></div>