簡體   English   中英

如何遍歷 DOM 並顯示所有標簽?

[英]How To Traverse the DOM and display all tags?

我想 go 圍繞 DOM 樹,並顯示其所有元素及其繪圖。 我堅持這個解決方案,但它很糟糕。 我需要做一個遞歸的function,但我不擅長。

節目結果

 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>

這是一個遞歸實現,它檢查每個“父”元素以查看它是否有超過0個子元素。 如果是這樣,遍歷子代並調用 function 並設置“新”父代。

 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>

如果您使用document.querySelectorAll("*")則不需要遞歸。

我用遞歸ZC1C425268E68385D1AB5074C174C17A94F14Z添加了第二個(縮進的解決方案),我以“咖喱”方式編寫了:ZC1C1C425268EE6838EE68385D1AB5074C174C17A94CRTENM 1666666666 ANNFS ZC 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM