Reputation: 294
Why document.body.getElementById(idOfElem)
and document.body.getElementsByName(nameOfElem)
not working?
and
Why document.body.getElementByTagName(tagOfElem)
and document.body.getElementByClassName(classOfElem)
working?
When using the first, the browser throw this error:
TypeError: document.body.getElementById is not a function[Learn More]
Upvotes: 5
Views: 2309
Reputation: 31692
Since IDs are unique you have to use document.getElementById
as it is the only DOM element that have that function.
Elements other than document
have these functions: getElementsByTagName
, getElementsByClassName
, querySelector
and querySelectorAll
but not the getElementById
.
Why not define it on elements other than document?
An element with an ID is unique no matter what its parent is. Therefore, it's uncessary to know the parent of an element before getting that element using its ID. So, there's no need to put the function getElementById
on all elements, putting it only on document
will suffice.
Why are the other functions defined?
Because you sometimes need to get the <div>
s or <p>
s or elements with some class .cls
only if they're inside a known element. Then if you use document
as the root, the result will be all the elements in the document not just the ones inside your desired element.
Conclusion:
document.getElementById
will always return at most one element, hence why redefining it on every DOM element (it will be useless). But other functions like getElementsByTagName
, getElementByClassName
, ... could return as many as there could be. So we put them on all elements so that we can narrow the search by specifying a root to start the search from.
Upvotes: 6
Reputation: 718
getElementById
is a method of document
, not of document.body
. The same goes for getElementsByName
.
On the other hand, getElementByTagName
and getElementByClassName
can be called on any element including body
.
Upvotes: 3
Reputation: 4236
document.body.getElementById()
does not exist.
Use document.getElementById()
gets the element with the matching ID from the document.
document.getElementsByTagName()
- gets all the elements which match the tag name from the document.
Upvotes: 0