简体   繁体   English

使用Javascript获取所有html标签

[英]Get all html tags with Javascript

Does anybody knows how can I get all the HTML tags that exist in a page? 有谁知道如何获取页面中存在的所有HTML标记? I need to get only the tags without their IDs or other attributes, and create a kind of tree-structure of them. 我只需要获取没有ID或其他属性的标签,并创建一种树形结构。 Prefer to do that with Javascript or JQuery. 喜欢用Javascript或JQuery做到这一点。

For example, This HTML code: 例如,此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>

should return return: 应该返回:

html HTML
head
title 标题
body 身体
h1 H1
div DIV
table
tr TR
td TD

You can pass a * to getElementsByTagName() so that it will return all elements in a page: 您可以将*传递给getElementsByTagName()以便它返回页面中的所有元素:

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

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

Its a very simple piece of Javascript 它是一个非常简单的Javascript

document.querySelectorAll('*')

Try it out in the console log and it will show you all the tags in the document. 在控制台日志中尝试它,它将显示文档中的所有标记。

Another example is to getElementsByTagName 另一个例子是getElementsByTagName

These do print out into an array, so you can then loop through the elements and doing different things on different elements. 这些会打印成一个数组,因此您可以遍历元素并在不同的元素上执行不同的操作。

Example: 例:

var items = document.getElementsByTagName("*");
for (var i = 0; i < items.length; i++) {
    //do stuff
}

我使用getElementsByTagName.tagName为返回数组中的每个值执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM