Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No getElementById for body?

Tags:

javascript

dom

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.

like image 818
Derek 朕會功夫 Avatar asked Jun 27 '12 22:06

Derek 朕會功夫


1 Answers

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 id in the document, this why getElementById is a method of document.

Example:

<body>
    <div id="start">
        <span class="a">
    </div>
    <div class="a">
    </div>
</body>

Start searching for class a from 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 typeof comparing:

typeof 1 == typeof 2 == "Number" // true
1 !== 2 // true.

typeof only checks for the type, not the value, document and document.body are both objects, but different objects.

typeof document === typeof document.body === typeof null === "object" // true
document === document.body // false!!!

As you can see, null and document share the same type, but do they have the same methods...? NO

like image 105
gdoron is supporting Monica Avatar answered Sep 19 '22 00:09

gdoron is supporting Monica