I have the following html structure
<div id="container">
<div id="child_1" data-customId="100">
</div>
<div id="child_2" data-customId="100">
</div>
<div id="child_3" data-customId="100">
</div>
<div id="child_4" data-customId="20">
</div>
<div id="child_5" data-customId="323">
</div>
<div id="child_6" data-customId="14">
</div>
</div>
And what I want to do is to get the count of child divs that contains different data attribute. For example, I’m trying this:
$(`div[id*="child_"]`).length); // => 6
But that code is returning 6 and what I want to retrieve is 4, based on the different data-customId. So my question is, how can I add a filter/map to that selector that I already have but taking into consideration that is a data-attribute.
I was trying to do something like this:
var divs = $(`div[id*="child_"]`);
var count = divs.map(div => div.data-customId).length;
2
Answers
You’ll have to extract the attribute value from each, then count up the number of uniques.
No need for jQuery for something this trivial, though.
Note that the property
customid
is lower-cased in the JavaScript. This could be an easy point of confusion. You might consider changing your HTML fromto
so that you can use
customId
in the JS (to follow the common conventions).After you getting the
child-divs
map theircustomid
and just get the length ofunique values
:Note:
$
is equivalent todocument.querySelectorAll
injs
returns a NodeList that’s why I destructure it by the three dots...