0

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');
    }
  });
  • Do you have `filters` declared anywhere? using ${} inside of \` will interpret any variables, so \`${filters}\` would put in the value of `filters` – Zach J. Nov 03 '22 at 21:37
  • 2
    And with what part do you have problems with? With [`match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match), with [`join`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) or with [Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)? – t.niese Nov 03 '22 at 21:38
  • The `const filters = [...document.querySelectorAll('.btn.active')].map( (el) => el.dataset.filter, );` is declared here yes. It's like classical music or Renaissance, ... –  Nov 03 '22 at 21:39
  • Well I don't understand those `match` and `join ` in this context. Don't get what it matches and joins –  Nov 03 '22 at 21:40
  • Without knowing the contents of `filters` it is not possible to tell you what it exactly does. – t.niese Nov 03 '22 at 21:41
  • For those wondering, here is the last approved answer for this code: https://stackoverflow.com/a/74306849/3684265 – imvain2 Nov 03 '22 at 21:41
  • 1
    Just to help you if your are a beginner, I wouldn’t recommend you just using code you don’t understand and copied from anywhere – HackerFrosch Nov 03 '22 at 21:42
  • @Sumin If you ask followup a question it would be greate to link to original question. – t.niese Nov 03 '22 at 21:43
  • Based on the previous question matches is about [`Element.matches`](https://developer.mozilla.org/en-US/docs/Web/API/Element/matches)? – t.niese Nov 03 '22 at 21:46
  • Yes, about the `element.matches` . –  Nov 03 '22 at 21:49
  • 1
    `element.matches(selector)` returns true if the element matches the CSS selector. – Barmar Nov 03 '22 at 21:50

1 Answers1

0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612