How do I iterate through children elements of a div using jQuery?

后端 未结 7 1280
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 01:28

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

相关标签:
7条回答
  • 2020-11-28 01:45

    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.

    0 讨论(0)
  • 2020-11-28 01:53

    children() is a loop in itself.

    $('.element').children().animate({
    'opacity':'0'
    });
    
    0 讨论(0)
  • 2020-11-28 01:57

    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 () { /* ... */ });
    
    0 讨论(0)
  • 2020-11-28 01:58
    $('#myDiv').children().each( (index, element) => {
        console.log(index);     // children's index
        console.log(element);   // children's element
     });
    

    This iterates through all the children and their element with index value can be accessed separately using element and index respectively.

    0 讨论(0)
  • 2020-11-28 02:00

    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

    0 讨论(0)
  • 2020-11-28 02:02

    It can be done this way as well:

    $('input', '#div').each(function () {
        console.log($(this)); //log every element found to console output
    });
    
    0 讨论(0)
提交回复
热议问题