I want to select all elements with class name find-me and group them in separate arrays (or NodeLists) based on their other classes, if idential. Here is an example:
<div class="find-me one two">
Element 1
</div>
<div class="find-me one two">
Element 2
</div>
<div class="find-me one two three">
Element 3
</div>
<div class="find-me one two three">
Element 4
</div>
<div class="find-me one two four">
Element 5
</div>
<div class="find-me one two">
Element 6
</div>
<div class="one two">
Element 7
</div>
My goal is to have:
- One array or NodeList with elements 1, 2 and 6 (
find-me, one, two) - One array or NodeList with elements 3 and 4 (
find-me, one, two, three) - One array or NodeList with element 5 (
find-me, one, two, four) - Element 7 should not be taken into account since it doesn't have the
find-meclass
I suppose I have to use document.querySelectorAll('.find-me') to first get a NodeList of all the elements I am interested in.
But then? I was thinking I could compare the list of classes from the current element with the previous one but how can I keep track of what element goes to what group? Any idea how to achieve that?
Sounds like a good opportunity to use
Object.groupBy, but be aware of its poor coverageUsing the same concept, you can write a reduce function to achieve the same goal, also the order/repetitive classes doesn't matter: