Reputation: 5605
Below is the div structure. How can I find the number of divs which has the id of _1item
only inside categoryFurniture
in javascript?
I tried this by doing some google research but no luck.
document.querySelectorAll('[id^=_1item]').length
div structure example:
<div id="categoryFurniture">
<div id= "xyz_1item"></div>
<div id= "abc_1item"></div>
<div id= "xyz_2item"></div>
<div id= "pqr_1item"></div>
<div id= "pqr_2item"></div>
</div>
<div id="categoryFruits">
<div id= "xyz_1item"></div>
<div id= "abc_2item"></div>
<div id= "xyz_3item"></div>
<div id= "pqr_1item"></div>
<div id= "pqr_3item"></div>
</div>
output should be 3
Upvotes: 2
Views: 2085
Reputation: 388446
You can use querySelectorAll with id and attribute ends selector
document.querySelectorAll('#categoryFurniture [id$=_1item]')
then you can read the length
property of the nodeList returned above to get the count
Demo: Fiddle
Upvotes: 4
Reputation: 18576
This will return you 3
as count
document.querySelector("#categoryFurniture").querySelectorAll('[id$=_1furniture]').length
or
document.querySelectorAll('#categoryFurniture [id$=_1furniture]').length
EDIT:
Based on your update on question, you need to replace _1furniture
with _1item
document.querySelectorAll('#categoryFurniture [id$=_1item]').length
Upvotes: 1