在指定的div - js内按id计算div的数量

时间:2022-02-15 11:15:45

Below is the div structure. How can I find the number of divs which has the id of _1item only inside categoryFurniture in javascript?

下面是div结构。如何在javascript中的categoryFurniture中找到id为_1item的div数?

I tried this by doing some google research but no luck.

我通过做一些谷歌研究尝试了这一点,但没有运气。

document.querySelectorAll('[id^=_1item]').length

div structure example:

div结构示例:

<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

输出应为3

2 个解决方案

#1


You can use querySelectorAll with id and attribute ends selector

您可以将querySelectorAll与id和属性结束选择器一起使用

document.querySelectorAll('#categoryFurniture [id$=_1item]')

then you can read the length property of the nodeList returned above to get the count

然后你可以读取上面返回的nodeList的length属性来获取计数

Demo: Fiddle

#2


This will return you 3 as count

这将返回3作为计数

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

根据您的问题更新,您需要将_1furniture替换为_1item

document.querySelectorAll('#categoryFurniture [id$=_1item]').length

#1


You can use querySelectorAll with id and attribute ends selector

您可以将querySelectorAll与id和属性结束选择器一起使用

document.querySelectorAll('#categoryFurniture [id$=_1item]')

then you can read the length property of the nodeList returned above to get the count

然后你可以读取上面返回的nodeList的length属性来获取计数

Demo: Fiddle

#2


This will return you 3 as count

这将返回3作为计数

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

根据您的问题更新,您需要将_1furniture替换为_1item

document.querySelectorAll('#categoryFurniture [id$=_1item]').length