Why use document.getElementById when I can directly refer to the DOM id in JavaScript? [duplicate]

自古美人都是妖i 提交于 2021-02-15 11:39:04

问题


Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?

I recently discovered that I can use in javascript any object from DOM with a direct reference to its id:

<div id="layer">IM A LAYER</div>
<script>
   alert(layer.innerHTML);
</script>

If this is true, what advantage I'd get using the getElementById method?


回答1:


Accessing a DOM element directly will give you a error if the element does not exist. Wheras if you use getElementById it will return NULL.

You also can't access all elements directly if they, for example, have dashes in their name (some-id), because JS variables can't contain dashes. You could however access tthem with window['some-id'].




回答2:


for example, if in your page you have elsewhere another previous script with

<script>
var layer = false; // or any other assignment
</script>

layer will be a reference to window.layer, then layer.innerHTML will fail. With document.getElementById you will avoid this tricky errors




回答3:


This will work only for id's containing letters allowed for variable names. For id's like text-11, or item-key-21 it won't work.



来源:https://stackoverflow.com/questions/14478102/why-use-document-getelementbyid-when-i-can-directly-refer-to-the-dom-id-in-javas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!