69

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?

1

2 Answers 2

117

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("*");
3
  • for unknown reason, it gives back a null
    – Kaiusee
    Commented Oct 10, 2012 at 18:39
  • 3
    @kkDev - If you call it AFTER the document has loaded (and thus when the DOM exists), it works. See jsfiddle.net/jfriend00/kKk3X for a working demo.
    – jfriend00
    Commented Oct 10, 2012 at 20:48
  • I get empty objects for some reason, even when using window.onload. Commented Feb 2, 2022 at 23:57
42

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 > *' );
4
  • 8
    document.body.getElementsByTagName('*') may be more performant.
    – Rob W
    Commented Oct 10, 2012 at 15:44
  • 2
    @RobW: …and more cross-browser compatible
    – Bergi
    Commented Oct 10, 2012 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 excludes text nodes etc (but it includes comment nodes in <=IE8 (bug))). (and Bergi is right, QSA is supported since IE 8).
    – Rob W
    Commented Oct 10, 2012 at 15:50
  • 4
    It should be noted that querySelectorAll() and getElementsByTagName() have a different return type. querySelectorAll returns a NodeList, while getElementsByTagName returns an HTMLCollection. More on the differences between the two here: Difference between HTMLCollection, NodeLists, and arrays of objects
    – zcoop98
    Commented Sep 3, 2021 at 21:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.