【问题标题】:how to loop over the child divs of a div and get the ids of the child divs?如何遍历 div 的子 div 并获取子 div 的 id?
【发布时间】:2012-07-02 09:51:06
【问题描述】:

我有一个 id 为 test 的 div

通过 foreach 循环,我在测试 div 中创建了一些内部 div。所以就变成了这个样子。

<div id="test">
<div id="test-1"></div>
<div id="test-2"></div>
<div id="test-3"></div>
<div id="test-4"></div>
</div>

我在 javascript 函数中获取父 div id “test”。现在我想遍历测试div的内部div(子div),并一一获取每个div的id并通过javascript设置它们的样式。

对此有什么想法吗?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    试试这个

    var childDivs = document.getElementById('test').getElementsByTagName('div');
    
    for( i=0; i< childDivs.length; i++ )
    {
     var childDiv = childDivs[i];
    }
    

    【讨论】:

    • 有效,但需要在 i 之前声明。应该是for( var i=0; i&lt; childDivs.length; i++ )
    【解决方案2】:

    您可以使用 jQuery .each() 函数循环遍历内部 div。以下示例执行此操作,并为每个内部 div 获取 id 属性。

    $('#test').find('div').each(function(){
        var innerDivId = $(this).attr('id');
    });
    

    【讨论】:

      【解决方案3】:

      如果有人还在寻找,这就是解决方案

      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-'));
      

      【讨论】:

        【解决方案4】:

        你可以使用

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

        each()

        以这种方式为例:

        $('[id^=test-]').each(function(){
            var atId = this.id;
            // do something with it
        });​
        

        【讨论】:

          【解决方案5】:

          您正在尝试做的是循环通过 #test div 的直接后代 div;您可以使用 &gt; 后代选择器和 jQuery .each() 迭代器来执行此操作。您还可以使用 jQuery .css().attr() 方法分别设置和检索 id。

          $("#test > div").each(function(index){
              var id = $(this).attr("id");
              $(this).css(/* apply styles */);
          });
          

          【讨论】:

            【解决方案6】:

            使用 jQuery。

            此代码可以根据您的需要添加:

            $testDiv = ​$('div#test')​​​​​​​​​​​​.first();    
            $('div', $testDiv).css("margin", '50px');​​​​
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2023-03-17
              • 2015-08-30
              • 2016-07-23
              • 2012-07-22
              • 2013-01-27
              • 2021-09-05
              相关资源
              最近更新 更多