Home > Enterprise >  What does this piece of code mean? (c.matches(`.${filters.join('.')}`))
What does this piece of code mean? (c.matches(`.${filters.join('.')}`))

Time:11-04

I have a JavaScript code to filter some divs with some buttons, but I don't really understand what this piece of code means.

c.matches(`.${filters.join('.')}`)

The full code of that part is:

sheets.forEach((c) => {
    if (filters.length === 0 || c.matches(`.${filters.join('.')}`)) {
      c.classList.remove('hidden');
    } else {
      c.classList.add('hidden');
    }
  });

CodePudding user response:

filters is an array of class names, and filters.join('.') will concatenate them all with . between them. The template literal will put . before this. So if filters is ['class1', 'class2', 'class3'], the resulting string will be .class1.class2.class3.

The Element.matches() method returns true if the element matches the given CSS selector. So in the above example, this is c.matches('.class1.class2.class3') if the element c has all 3 classes.

So what this code does is filter the sheets so that only the ones matching all the classes in the filter list are shown.

  • Related