How do I iterate through child elements of a div u

2019-01-08 03:43发布

I have a div and it has several input elements in it... I'd like to iterate through each of those elements. Ideas?

6条回答
叛逆
2楼-- · 2019-01-08 03:58

Use children() and each(), you can optionally pass a selector to children

$('#mydiv').children('input').each(function () {
    alert(this.value); // "this" is the current element in the loop
});

You could also just use the immediate child selector:

$('#mydiv > input').each(function () { /* ... */ });
查看更多
再贱就再见
3楼-- · 2019-01-08 04:11

I don't think that you need to use each(), you can use standard for loop

var children = $element.children().not(".pb-sortable-placeholder");
for (var i = 0; i < children.length; i++) {
    var currentChild = children.eq(i);
    // whatever logic you want
    var oldPosition = currentChild.data("position");
}

this way you can have the standard for loop features like break and continue works by default

also, the debugging will be easier

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-08 04:14

It is also possible to iterate through all elements within a specific context, no mattter how deeply nested they are:

$('input', $('#mydiv')).each(function () {
    console.log($(this)); //log every element found to console output
});

The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.

查看更多
Viruses.
5楼-- · 2019-01-08 04:20

children() is a loop in itself.

$('.element').children().animate({
'opacity':'0'
});
查看更多
Ridiculous、
6楼-- · 2019-01-08 04:23

It can be done that way as well.
$('input', '#div').each(function () { console.log($(this)); //log every element found to console output });

查看更多
Luminary・发光体
7楼-- · 2019-01-08 04:25

If you need to loop through child elements recursively:

function recursiveEach($element){
    $element.children().each(function () {
        var $currentElement = $(this);
        //////////// Show element
        console.info($currentElement);
        //////////// Show events handlers of current element
        console.info($currentElement.data('events'));
        //////////// Loop her children
        recursiveEach($currentElement);
    });
}

//////////// Parent div
recursiveEach($("#div"));   

NOTE: In this example I show the events handlers registered with an object.

查看更多
登录 后发表回答