如何在javascript中获取特定子元素的数量

时间:2014-07-22 05:29:02

标签: javascript

这是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中的变量传递。有人可以帮帮我..

2 个答案:

答案 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);

演示:: jsFiddle using jQuery

答案 1 :(得分:1)

如果你不使用&lt; IE8和旧的Opera浏览器,那么你可以轻松使用

document.querySelectorAll('figure img').length

P.S。安全版

var frag = document.querySelectorAll('figure img'),
           counter = (frag === null) ? 0 : frag.length;