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-me
class
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?
2
Answers
You can use this code:
You can iterate through each element in the NodeList then for each element, extract its classList and convert it into a string so you can use it as a key in an object. If an array already exists for that particular combination of classes, push the element into that array. If not, create a new array (or NodeList) and add the element to it.
Demo: