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?
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.
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.
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.
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.
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("*");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With