简体   繁体   中英

How do i get the number of specific child elements in javascript

Here is the 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>

What i need to do is get count of number of child elements inside figure element and not select the figcaption element which also happens to be the child of figure , so that i can further create a loop and pass on the 'number of image items' as a variable in JavaScript. Could someone please help me..

use getElementsByTagName , try:

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

Demo:: JsFiddle

if you are using jQuery, do:

var imgLength = $(".product_grid_list").find("figure > img").length;
alert(imgLength);

Demo:: jsFiddle using jQuery

If you don't use < IE8 and old opera browsers, then you can easily use just

document.querySelectorAll('figure img').length

PS safe version

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM