I have the following html structure
JavaScript
x
15
15
1
<div id="container">
2
<div id="child_1" data-customId="100">
3
</div>
4
<div id="child_2" data-customId="100">
5
</div>
6
<div id="child_3" data-customId="100">
7
</div>
8
<div id="child_4" data-customId="20">
9
</div>
10
<div id="child_5" data-customId="323">
11
</div>
12
<div id="child_6" data-customId="14">
13
</div>
14
</div>
15
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:
JavaScript
1
2
1
$(`div[id*="child_"]`).length); // => 6
2
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:
JavaScript
1
3
1
var divs = $(`div[id*="child_"]`);
2
var count = divs.map(div => div.data-customId).length;
3
Advertisement
Answer
After you getting the child-divs
map their customid
and just get the length of unique values
:
JavaScript
1
7
1
let divs = document.querySelectorAll(`div[id*="child_"]`);
2
let idCustoms = [divs].map(div=>div.dataset.customid);
3
//idCustoms: ["100", "100", "100", "20", "323", "14"]
4
//get unique values with Set
5
console.log([ new Set(idCustoms)].length);//4
6
//or with filter
7
console.log(idCustoms.filter((item, i, ar) => ar.indexOf(item) === i).length);//4
JavaScript
1
14
14
1
<div id="container">
2
<div id="child_1" data-customId="100">
3
</div>
4
<div id="child_2" data-customId="100">
5
</div>
6
<div id="child_3" data-customId="100">
7
</div>
8
<div id="child_4" data-customId="20">
9
</div>
10
<div id="child_5" data-customId="323">
11
</div>
12
<div id="child_6" data-customId="14">
13
</div>
14
</div>
Note: $
is equivalent to document.querySelectorAll
in js
returns a NodeList that’s why I destructure it by the three dots ...