这是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
元素,这也恰好是figure
的子元素,所以我可以进一步创建一个循环并将“图像项数”作为JavaScript中的变量传递。有人可以帮帮我..
答案 0 :(得分:2)
使用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);
答案 1 :(得分:1)
如果你不使用&lt; IE8和旧的Opera浏览器,那么你可以轻松使用
document.querySelectorAll('figure img').length
P.S。安全版
var frag = document.querySelectorAll('figure img'),
counter = (frag === null) ? 0 : frag.length;