之前,我已经知道可以通过class名称获取元素。
document.body.getElementsByClassName("foo");
我非常懒,所以我只是复制并粘贴代码到其他部分来完成这个任务。
document.body.getElementById("bar");
我无意中发现它不起作用。我进行了测试,结果显示:
TypeError: Object #<HTMLBodyElement> has no method 'getElementById'
那么为什么它有getElementsByClassName
、getElementsByTagName
和所有类似的方法,但只没有getElementById
呢?
typeof document === typeof document.body //true
它们的类型相同,因此它们应该拥有相同的东西。但是在这里似乎并非如此。
typeof
对这两个值都返回"object"
,这意味着它们可以是任何类型的对象。它并不告诉你它们具有哪些方法。 - pimvdbtypeof document === typeof document.body === typeof null === typeof [] === "object"
。 - nicosantangelo