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]
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.
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