Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all elements in the body tag using pure javascript

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?

like image 970
Kaiusee Avatar asked Oct 10 '12 15:10

Kaiusee


People also ask

How do you get all the elements in a page using JS?

First select all elements using $('*') selector, which selects every element of the document. Use . each() method to traverse all element and check if it has ID. If it has ID then push it in the array.

How do I get all the elements in the DOM?

To get all DOM elements by an attribute, use the querySelectorAll method, e.g. document. querySelectorAll('[class="box"]') . The querySelectorAll method returns a NodeList containing the elements that match the specified selector.

How do I get all the elements in a page?

You used getElementById() to retrieve an element with a specific ID, getElementsByTagName() to get all the elements of a certain type, and getElementsByName() to find all elements with a particular name attribute.

Why is document body null?

body object, it is most likely because the body has not been defined yet. If document. body is null, you most likely need to execute your code in the window.


1 Answers

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("*"); 
like image 126
jfriend00 Avatar answered Oct 04 '22 01:10

jfriend00