【问题标题】:How to loop throug all elements inside a div [duplicate]如何循环遍历 div 内的所有元素 [重复]
【发布时间】:2019-06-24 17:08:38
【问题描述】:

我想遍历div 中的所有元素。我用这段代码试过了,但它只返回主/开始div

这段代码有什么问题?

<div id="startcontainer">
  <div>anotherone</div>
  <div>
    one more <span>a span tag<a href="">href tag</a></span>
  </div>

  $('#startcontainer').each(function(index, value){ console.log(index+''+value+'-> id:'+$(this).attr("id")+'
  tag:'+$(this).prop("tagName")); });
</div>

【问题讨论】:

  • 最快的方法是不这样做。为什么要为每个元素添加一个 id?这对于 HTML 验证不是强制性的
  • 我将在最后删除这个 id。我需要一个 id 让每个元素都更容易工作,这个网站上的所有东西都更容易
  • 如果你要执行一些任务或样式,你只需要添加一个 ID 或类,除此之外没有理由你也添加一个 ID
  • 它变得更简单,所以我知道每个元素都有一个 id,无需检查 id==undefined 或 class 是否未定义等来切换到另一个选择器 - 我认为这是一种简单的方法让它更简单
  • @mikeD 想要持久化最后一个给定的 id 吗?

标签: javascript jquery


【解决方案1】:

你需要递归搜索,这里我做了一个例子。

var foo = document.getElementById('startcontainer');

function search(element){

$(element).children().each(function(index, item){
console.log(item.tagName);
search(item) // Search agen for children, this is recursive search so it will go throw each element and its cheldren
});
}

search(foo)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="startcontainer">
  <div>anotherone</div>
  <div>
    one more <span>a span tag<a href="">href tag</a></span>
  </div>
 </div>

【讨论】:

  • 非常感谢,我想我用一个简单的 each() 来做...
  • 当然可以,但我是个邻居,我不能投票 ;-)
【解决方案2】:

你有使用孩子 https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children

喜欢这个

var foo = document.getElementById('startcontainer');
for (let i = 0; i < foo.children.length; i++) {
  console.log(foo.children[i].tagName);
}

在 jquery 中你可以从中得到灵感 https://api.jquery.com/children/

【讨论】:

  • 嗨,谢谢,我和孩子一起尝试过,但我只得到第一个孩子,我需要所有可以无限嵌套的孩子 - 我怎么能做到这一点?
【解决方案3】:

您可能不得不尝试这种方式。

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="startcontainer">
      <div>anotherone</div>
      <div>
        one more <span>a span tag<a href="">href tag</a></span>
      </div>
    </div>
    
    <script>
            $('#startcontainer').children().each(function(index, value){
           console.log(index, " ", value)
        });
        </script>

Reference

【讨论】:

  • 嗨,是的,但我只得到第一个孩子,我需要无限嵌套元素的所有孩子 - 我必须做什么才能得到这个?
猜你喜欢
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 2021-07-31
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多