如何仅选择JQuery中的第一级子级 [英] How to select only the first level children in JQuery

查看:178
本文介绍了如何仅选择JQuery中的第一级子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在DOM中具有以下结构,并且我只想从指定的类中选择第一级子级.如何在JQuery中做到这一点?

I have the following structure in my DOM and I would like to select only the first level children from a specified class. How to do this in JQuery?

请注意,我嵌套的div具有相同的CSS类.

Please note that I have nested divs with same css class.

我的HTML:

<div class="t">
    <div>title</div>
    <div class="ch">
        <input type="text name="input1" value="" id="i1">
    </div>
    <div class="t">
        <div>sub title</div>
        <div class="ch">
            <input type="text name="input2" value="" id="i2">
        </div>
    </div>
</div>

我需要获得什么: 当我找到所有类为't'的元素并进行迭代时,我想获得其下层为'ch'的孩子(而不是内层div中的那些为't'的孩子).

What I need to get: When I find all elements with class 't' and iterate, I want to get the children with class 'ch' that are under (not the ones in the inner div with class 't').

JavaScript

$(".t").each(function() {
    //Get the elements in '.ch' for $(this) and process.
});

感谢您的帮助.

推荐答案

您可以使用children选择器

类似

$('.t').children('.ch')

这等效于

$('.t > .ch') // Child selector

和可以从码作为选择器选择删除环你正在寻找的元素.

And you can remove the each loop from the code as the selector selects the elements you are looking for.

修改

对于第一级,您可以结合使用child selectorparents方法

For First level you can use a combination of child selector and parents method

$('.t > .ch').filter(function() {
   return $(this).parents('.t').length === 1 
})

检查小提琴

Check Fiddle

这篇关于如何仅选择JQuery中的第一级子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆