简体   繁体   English

jQuery获取元素的第一个孩子

[英]jQuery get first children of element

here is my html这是我的 html

<div class="start">
    <div> <!-- this -->
        <div></div>
    </div>
    <div></div> <!-- this -->
    <div> <!-- this -->
        <div>
            <div></div>
        </div>
    <div>
<div>

I need to collect all the selected div , and I can do it with $('div[class="start"] > div') , but how to do it in a .each() cycle, because I'm cycling on all the div[class="start"]' .我需要收集所有选定的div ,我可以用$('div[class="start"] > div')来完成,但是如何在.each()循环中完成,因为我正在骑自行车所有div[class="start"]'

$('div[class="start"]').each(function(){
    doSomething($(this));
    //this below is what I want to achieve
    $(this).children('> div').each(function(){
         doSomethingElse($(this));
    });
});

Use children使用children

$('div.start').children().each(function() {

This will select all the direct children of the div having class start .这将选择具有 class startdiv所有直接子级。

There is no need of using attribute-value selector here, you can use class selector.这里不需要使用属性值选择器,你可以使用类选择器。

You just need to remove > or > div你只需要删除>> div

$('div[class="start"]').each(function(){
    doSomething($(this));
    //this below is what I want to achieve
    $(this).children().each(function(){
        doSomethingElse($(this));
    });
});

Your code is more or less correct but instead of children() you need to use find()您的代码或多或少是正确的,但您需要使用 find() 而不是 children()

$('div[class="start"]').each(function(){
    doSomething($(this));
    //this below is what I want to achieve
    $(this).find('> div').each(function(){
         doSomethingElse($(this));
    });
});

JSFiddle JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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