Get all elements in the body tag using pure javascript

JavascriptHtml

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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("*");

Solution 2 - Javascript

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 > *' );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKaiuseeView Question on Stackoverflow
Solution 1 - Javascriptjfriend00View Answer on Stackoverflow
Solution 2 - JavascriptSirkoView Answer on Stackoverflow