Home > Web Front-end > JS Tutorial > js method to get html page node (recursive method)

js method to get html page node (recursive method)

高洛峰
Release: 2017-02-08 15:29:44
Original
1102 people have browsed it

I haven’t operated recursive calls in a long time. After reading it, I suddenly woke up!

The code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>统计Element节点</title>
   <script language="javascript">
         var  elementName="";
   function countTotalElement(node)
   {
       ///Attribute  nodeType值为2,表示节点属性
    ///Comment    nodeType值为8,表示注释文本
    ///Document   nodeType值为9,表示Document
    ///DocumentFragment   nodeType值为11,表示Document片段
    ///Element            nodeType值为1,表示元素节点
    ///Text               nodeType值为3,表示文本节点
       var total=0;
    if(node.nodeType==1) //1代表节点的类型为Element
    {
       total++;
    elementName=elementName+node.tagName+"\r\n";

    }

    var childrens=node.childNodes;
    for(var i=0;i<childrens.length;i++)
    {
        total+=countTotalElement(childrens[i]);
    } 
    return total;
   }
   </script>
</head>
<body>
     <h1>测试</h1>
     <table width="100" border="2" cellpadding="0" cellspacing="0">
         <tr><td>
         <form name="form1" action="" method="post">
               <input type="text" name="ipput1" value="测试"><br />
               <input type="password" name="password" value="">
         </form>
         </td></tr>
     </table>
     <a href="javascript:void(0)" onClick="alert(&#39;标记总数&#39;+countTotalElement(document)+&#39;\r\n 全部标记如下:\r\n&#39;+elementName);">开始测试</a>
</body>
</html>
Copy after login

In fact, the same effect as Baidu spider crawler can also be achieved through recursive calls! This is worth a try. Maybe you can use this method to write a sitemap generator!

For more js-related articles on how to get html page nodes (recursively), please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template