简体   繁体   中英

Get all html tags with Javascript

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.

For example, This HTML code:

<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
head
title
body
h1
div
table
tr
td

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
}

Its a very simple piece of 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

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为返回数组中的每个值执行此操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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