how to loop over the child divs of a div and get the ids of the child divs?

后端 未结 6 1674
你的背包
你的背包 2020-12-16 12:20

I have a div with id test

and through the foreach loop I am creating some inner divs inside the test div. So it becomes like this.

相关标签:
6条回答
  • 2020-12-16 12:57

    You can loop through inner divs using jQuery .each() function. The following example does this and for each inner div it gets the id attribute.

    $('#test').find('div').each(function(){
        var innerDivId = $(this).attr('id');
    });
    
    0 讨论(0)
  • 2020-12-16 12:57

    You can use

    $('[id^=test-]')
    

    and each()

    this way for example :

    $('[id^=test-]').each(function(){
        var atId = this.id;
        // do something with it
    });​
    
    0 讨论(0)
  • 2020-12-16 12:57

    What you are trying to do is loop through the direct-descendant divs of the #test div; you would do this using the > descendant selector, and the jQuery .each() iterator. You can also use the jQuery .css() and .attr() methods for styling and retrieving the id respectively.

    $("#test > div").each(function(index){
        var id = $(this).attr("id");
        $(this).css(/* apply styles */);
    });
    
    0 讨论(0)
  • 2020-12-16 13:08

    Try this

    var childDivs = document.getElementById('test').getElementsByTagName('div');
    
    for( i=0; i< childDivs.length; i++ )
    {
     var childDiv = childDivs[i];
    }
    
    0 讨论(0)
  • 2020-12-16 13:13

    Use jQuery.

    This code can be addapted to your needs:

    $testDiv = ​$('div#test')​​​​​​​​​​​​.first();    
    $('div', $testDiv).css("margin", '50px');​​​​
    
    0 讨论(0)
  • 2020-12-16 13:19

    Here's the solution if somebody still looks for it

    function getDivChildren(containerId, elementsId) {
        var div = document.getElementById(containerId),
            subDiv = div.getElementsByTagName('div'),
            myArray = [];
    
        for(var i = 0; i < subDiv.length; i++) {
            var elem = subDiv[i];
            if(elem.id.indexOf(elementsId) === 0) {
                myArray.push(elem.id);
            }
        }
        return myArray;
    }
    console.log(getDivChildren('test', 'test-'));
    
    0 讨论(0)
提交回复
热议问题