这是 Html..
<figure>
<img class="hover_active" src="http://placehold.it/360x480&text=image+1" alt="">
<img src="http://placehold.it/360x480&text=image+2" alt="">
<img src="http://placehold.it/360x480&text=image+3" alt="">
<img src="http://placehold.it/360x480&text=image+4" alt="">
<img src="http://placehold.it/360x480&text=image+5" alt="">
<figcaption>
<h5>Product Name</h5>
<p>Rs. <span class="original_price">2,000</span></p>
</figcaption>
</figure>
我需要做的是获取 figure
元素内子元素的数量,而不是选择 figcaption
元素,它也恰好是 的子元素图
,以便我可以进一步创建循环并将“图像项数”作为 JavaScript 中的变量传递。有人可以帮我吗..
最佳答案
使用getElementsByTagName ,尝试:
var len = document.getElementsByTagName("figure")[0].getElementsByTagName("img").length;
//document.getElementsByTagName("figure")[0] --> get first 'figure' tag
//.getElementsByTagName("img") --> get all 'img' elements inside first 'figure' tag
//.length --> get the length of 'img' elements
演示::JsFiddle
如果您使用 jQuery,请执行以下操作:
var imgLength = $(".product_grid_list").find("figure > img").length;
alert(imgLength);
关于javascript - 如何获取javascript中特定子元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24879572/