Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getElementById not work on elements inside the document element? [duplicate]

If you use getElementById to with document like - document.getElementById then it always works.

But however, if we perform the same on an element say x like x.getElementById, then it returns an error.

The unusual thing about this is that getElementsByClassName and getElementsByTagName work on the elements however getElementById doesn't!

like image 249
akash4eva Avatar asked May 10 '13 05:05

akash4eva


People also ask

Why is document getElementById not working?

This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element. The solution is that you need to put your JavaScript code after the closure of the HTML element or more generally before < /body > tag.

Can you use getElementById twice?

You can call getElementById multiple times and it will work.

What does getElementById return if there is no such element with that ID?

If there is no element with the given id , this function returns null . Note that the id parameter is case-sensitive, so document. getElementById("Main") will return null instead of the element <div id="main"> because "M" and "m" are different for the purposes of this method.

Can I have duplicate ids in HTML?

You can't have the same id multiple times. Use class instead. Show activity on this post. COMPONENTS: if you write reusable component e.g. ) in your example then if you put two ore more components into one document then you will get INVALID html.


1 Answers

Container IDs should be unique, so there's no reason to find an object by ID within another container. This is why you only need document.getElementById to access any element by its ID, whereas when you are searching by class or tag name, you might want to only search within a specific container, which is why you can do x.getElementsByClassName etc.

like image 102
mash Avatar answered Oct 12 '22 12:10

mash