63

I'm trying to get all the elements (tags) inside the Body tag of an HTML page in an array using pure javascript. I mean without using any framework (ex. JQuery).

I've found that you can use document.all but that will return all the elements inside the whole document including the scripts.

Is there anyway I can get those tags?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Kaiusee
  • 1,253
  • 1
  • 14
  • 28
  • 2
    Possible duplicate of [Javascript: How to loop through ALL DOM elements on a page?](http://stackoverflow.com/questions/4256339/javascript-how-to-loop-through-all-dom-elements-on-a-page) – Ashraf Sada Sep 05 '16 at 06:59

2 Answers2

109

If you want all elements inside the body tag, not just first level children, you can simply use getElementsByTagName() with a wildcard:

var elems = document.body.getElementsByTagName("*");
jfriend00
  • 683,504
  • 96
  • 985
  • 979
40

You can use document.querySelectorAll() for that.

If you really want all (including nested tags), use this

 var elements = document.querySelectorAll( 'body *' );

If you only want the immediate child nodes, use

 var elements = document.querySelectorAll( 'body > *' );
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • 7
    `document.body.getElementsByTagName('*')` may be more performant. – Rob W Oct 10 '12 at 15:44
  • 2
    @RobW: …and more cross-browser compatible – Bergi Oct 10 '12 at 15:46
  • 2
    user1689607 posted an answer suggesting **`.children`** (for some reason, he deleted it). I prefer the `.children` property over the methods suggested in this answer, because it's more concise and more obvious (`.children` opposed to QSA / getElementsByTagName("*")`. And, after all, the `children` property exists because it ought to be used when one is looking for child **elements** ([`.children`](https://developer.mozilla.org/en-US/docs/DOM/Element.children) excludes text nodes etc (but it includes comment nodes in <=IE8 (bug))). (and Bergi is right, QSA is supported since IE 8). – Rob W Oct 10 '12 at 15:50
  • 4
    It should be noted that `querySelectorAll()` and `getElementsByTagName()` have a *different return type*. `querySelectorAll` returns a [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList), while `getElementsByTagName` returns an [`HTMLCollection`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection). More on the differences between the two here: [Difference between HTMLCollection, NodeLists, and arrays of objects](https://stackoverflow.com/q/15763358) – zcoop98 Sep 03 '21 at 21:28