使用Javascript获取所有html标签

问题描述:

有谁知道如何获取页面中存在的所有HTML标记?
我只需要获取没有ID或其他属性的标签,并创建一种树形结构。
首选使用Javascript或JQuery。

Does anybody knows how can I get all the HTML tags that exist in a page? I need to get only the tags without their IDs or other attributes, and create a kind of tree-structure of them. Prefer to do that with Javascript or JQuery.

例如,此HTML代码:

<html>
  <head>
    <title>
      Example Page 
  </title>
  </head>
  < body>
    <h1 style="somestyle">
      Blabla
  </h1>
  <div id="id">
    <table id="formid">
      <tr>
        <td>
        </td>
      </tr>
      </table>
  </div>
  </body>
</html>

应该返回:

html

head

title

body

h1

div
table

tr

td

您可以将 * 传递给 getElementsByTagName() 以便它返回页面中的所有元素:

You can pass a * to getElementsByTagName() so that it will return all elements in a page:

var all = document.getElementsByTagName("*");

for (var i=0, max=all.length; i < max; i++) {
     // Do something with the element here
}