查找特定元素中有多少个类

时间:2014-06-12 13:16:31

标签: jquery html css

我得到了这段代码:

$(document).ready(function () {
    $('.parent >' + '.child').each(function() {
        console.log($(this).length);
    });
});

我正在尝试记录child类中有多少parent个类。

这就是我的html代码:

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>

预期输出

5

实际输出

1
1
1
1
1

6 个答案:

答案 0 :(得分:3)

它只是

var elementsLength = $('.parent > .child').length

当你迭代时,你得到每个元素的长度,这是1,因为它一次只有一个元素

<强> 编辑:

我有点迷失,但基于下面的评论

$('.parent').each(function() {

    var elementsLength = $(this).children('.child').length

    if (elementsLength > 12) $(this).hide();

});

FIDDLE

编辑,再次:

隐藏溢出的元素更容易

$('.parent .child:gt(12)').hide();

FIDDLE

答案 1 :(得分:1)

您可以使用查找()长度

执行此操作

$(&#34; .parent&#34)。发现(&#34; .child&#34)。长度

如果您想在 EACH 中使用它 然后

$('.parent').find('.child').each(function(i) {
        console.log(i);
        if(i==12)
        {
            $(this).hide();
        }
    });

&#34; i&#34; 将是您代码中的元素编号

答案 2 :(得分:0)

使用length属性:

console.log( $('.parent >' + '.child').length);

答案 3 :(得分:0)

您可以使用此

       $(document).ready(function () {
             console.log($('.parent').childrens('.child').length);
       });

答案 4 :(得分:0)

试试这个......

var elemlength = $('.parent .child').length;

答案 5 :(得分:0)

jQuery选择器实际上返回一个DOM元素数组,因此您可以直接在选择器上运行length:

$('.parent > .child').length; //Returns 5

示例:http://jsfiddle.net/3NMAG/

相关问题