7

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

5
  • document.querySelectorAll('*'). or traverse the DOM (document.body) recursively with .children. Commented Mar 2, 2015 at 15:46
  • 2
    What is the use case for this? It is not trivial reproducing the DOM Commented Mar 2, 2015 at 15:53
  • developer.mozilla.org/en/docs/Web/API/TreeWalker Commented Mar 2, 2015 at 15:56
  • To clarify, do you want the output you described under "will return:", or an indented tree-like version of that? Commented Mar 2, 2015 at 15:58
  • It doesn't matter so much.. @NicolasMcCurdy, I tried to do this with querySelectorAll but it return a lot of junk with it and I need the tag name only. Commented Mar 3, 2015 at 8:02

3 Answers 3

11

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

1 Comment

And, just to add a little more info, each HTML element will have a "tagName" property that gives the basic name you're looking for. It's uppercase by default
0

I did it with getElementsByTagName and .tagName for every value in the return array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.