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

标签 jquery html css

我得到了这段代码:

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

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

这是我的 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

最佳答案

只是

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

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

编辑:

我有点迷茫,但根据下面的评论,类似

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

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

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

});

FIDDLE

再次编辑:

只 overflow hidden 的元素更容易

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

FIDDLE

关于jquery - 查找特定元素中有多少个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24185418/

相关文章:

javascript - 检测向下滚动

javascript - 我无法操作/选择通过 Ajax 调用加载的 div?

javascript - 从 Canvas 像素数据中获取错误的 RGB 值

php - :nth-child to target nested divs

javascript - 拖动元素时出现 Windows "disallowed"图标

javascript - jQuery:如何再次启用可放置

javascript - 如果所有方法都是私有(private)的,你如何测试 jQuery 插件?

javascript - 查找 ng-repeat 索引?

html - 如何在 Bootstrap 中将文本区域设置为最大宽度

css - 带有 -webkit-transform 的平行四边形菜单栏会导致多个错误