如何遍历DOM并显示所有标签?

时间:2019-10-28 16:41:07

标签: javascript html dom

我想遍历DOM树,并显示其所有元素及其图。 我坚持使用此解决方案,但这很糟糕。我需要做一个递归函数,但是我不擅长。

Result of program

const First = document.querySelector("*");
  for (var i = 0; i < First.children.length; i++) {
      console.log(First.children[i]);
  for (var j = 0; j < First.children[i].children.length; j++) {
    if (First.nodeType == 1) {
       console.log(First.children[i].children[j]);
    }
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
  <h1>Header</h1>
  <p>Some text
     <a href="#">References</a>
  </p>
  <ul id="myList">
    <li>One</li>
    <li>Two</li>
    <li>Tree</li>
  </ul>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

这是一个替换性实现,它检查每个“父”元素是否具有超过0个子元素。如果是这样,则遍历子级并调用该函数并设置“新”父级。

function recursiveTagLister(parent = document.body, depth = 0){
  const indentation = (new Array(depth)).fill('&nbsp;').join("");
  console.log(indentation + parent.tagName);
  if(parent.children.length > 0){
    Array
    .from(parent.children)
    .forEach(item=>recursiveTagLister(item, depth+1));
  }
}

recursiveTagLister();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
  <h1>Header</h1>
  <p>Some text
     <a href="#">References</a>
  </p>
  <ul id="myList">
    <li>One</li>
    <li>Two</li>
    <li>Tree</li>
  </ul>
</body>
</html>

答案 1 :(得分:2)

如果您使用document.querySelectorAll("*"),则无需递归。

我使用递归函数(以“ curried”方式编写)为第二个(缩进)解决方案:函数rtl(ind)实际上返回了另一个带有父节点参数的(匿名)函数:

console.log([...document.querySelectorAll('*')].map(e=>e.nodeName).join(', '));

// for indentation use a modified recursive function 
// as written by kemicofa:

function rtl(ind=''){return function(parent=document.body){
  console.log(ind+parent.tagName);
  if(parent.children.length > 0){[...parent.children].forEach(rtl(ind+'  '));}
}}

rtl()();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
  <h1>Header</h1>
  <p>Some text
     <a href="#">References</a>
  </p>
  <ul id="myList">
    <li>One</li>
    <li>Two</li>
    <li>Tree</li>
  </ul>
</body>
</html>

相关问题