This question has disturbed me for a long time. Sorry if it is a stupid question.
Before, I have known that you can get the elements with a class name
document.body.getElementsByClassName("foo");
And I was so lazy, so I just copied and pasted the code to the other part to do this
document.body.getElementById("bar");
I accidentally found it won’t work. I tested and it says
TypeError: Object #<HTMLBodyElement> has no method ‘getElementById’
So why does it have getElementsByClassName andgetElementsByTagName and all those similar methods, but only no getElementById?
typeof document === typeof document.body //true
Their types are the same, so they should have the same thing. But it does not seem to be the case here.
You can have multiple elements with the same class name so narrowing down the search to start with a specific node make sense.
It doesn’t make sense with id because it it should be unique.
You can have only one
idin thedocument, this whygetElementByIdis a method ofdocument.Example:
Start searching for class
afrom the node<div id="start">will give you one element,While if you would have start from the top node- document, it would have ended with two elements.
Regarding to the
typeofcomparing:typeofonly checks for the type, not the value,documentanddocument.bodyare both objects, but different objects.As you can see,
nullanddocumentshare the same type, but do they have the same methods…? NO