SoFunction
Updated on 2025-03-03

Analysis of the instance of document hierarchical relationship printing in Javascript

This article describes the method of recursively printing Document hierarchical relationships in Javascript. Share it for your reference. The details are as follows:

<html xmlns="http:///1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Recursively display node hierarchy relationships</title>
<script type="text/javascript">
var ResultStr = "";
function ListNode(node,level) {
 PrintInfo(node, level);
 level++;
 var nodes = ;
 for (var i = 0; i < ; i++) {
  if (nodes[i].hasChildNodes()) {
   ListNode(nodes[i], level); //recursion  }
  else {
   PrintInfo(nodes[i], level);
  }
 }
}
function getSpace(level) {
 var s = "";
 for (var i = 0; i < level; i++) {
  s+="!----"
 }
 return s;
}
function PrintInfo(node, level) {
 ResultStr += getSpace(level) + "Name:" +  + 
 "...Type:" +  + "...Value:" +  + "<br />";
}
function getDocAllInfo() {
 ResultStr = "";
 ListNode(document, 0);
 (ResultStr);
}
</script>
</head>
<body>
<input type="button" value="test" onclick="getDocAllInfo()" />
<div >divcontent</div>
<table>
  <tr>
    <td>Cell1</td>
    <td>Cell2</td>
  </tr>
  <tr>
    <td>Cell3</td>
    <td>Cell4</td>
  </tr>
</table>
<input type="text" />
<span>I amSPAN</span>
<!--I am注释-->
</body>
</html>

I hope this article will be helpful to everyone's JavaScript programming.