【问题标题】:Traversing web page in javascript [duplicate]在javascript中遍历网页[重复]
【发布时间】:2014-05-18 03:55:59
【问题描述】:

可能重复:
How to iterate through a DOM tree?

你能告诉我如何用javascript编写以下伪代码吗?

for each child of <body>:
  if (tag.haschildren):
    for each tag.child:
       do some action;

谢谢

【问题讨论】:

  • 伪代码会对某些标签执行两次操作,是否需要?
  • @noiv11 这取决于 some_action 将是什么。
  • 不,无论 some_action 是什么,它都会被调用的频率超过标签的数量。

标签: javascript


【解决方案1】:
var els = document.getElementsByTagName("*");
for (var i = 0, ii = els.length; i < ii; i++) {
  for (var j = 0, jj = els[i].childNodes.length; j < jj; j++) {
    action(els[i].childNodes[j]);
  }  
}

【讨论】:

  • 可以逐级遍历吗?例如。 1) 2) body 的第一个子 Ch 3) 以这种方式到达叶子节点 4) 遍历所有叶子 5) 向上一级 6) 到叶子 7) 向上 8) 等等。
  • @xralf 是的,您可以随时自己编写。这是标准的深度优先树遍历。
  • 所以我会写这样的东西? var root = document.getElementsByTagName("body"); var subroot = root.childNodes; for (var i = 0, i &lt; root.childNodes.length; i++) { if subroot[i].hasChilden godown() ; else process(subroot[i]); ...}有没有测试节点离开的功能?
猜你喜欢
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
  • 2017-07-10
  • 2020-10-08
  • 2016-07-08
  • 2012-08-15
  • 1970-01-01
相关资源
最近更新 更多