当我可以在JavaScript中直接引用DOM ID时,为什么要使用document.getElementById? [英] Why use document.getElementById when I can directly refer to the DOM id in JavaScript?

查看:69
本文介绍了当我可以在JavaScript中直接引用DOM ID时,为什么要使用document.getElementById?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
IE/Chrome:DOM树元素在这里是全局变量吗?

我最近发现,我可以在javascript中使用DOM中直接引用其ID的任何对象:

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>

如果这是真的,那么使用getElementById方法可以获得什么好处?

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

推荐答案

如果该元素不存在,直接访问DOM元素将给您一个错误.如果您使用 getElementById ,它将返回 NULL .

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.

例如,如果所有元素的名称中都有破折号( some-id ),则也不能直接访问所有元素,因为JS变量不能包含破折号.但是,您可以使用 window ['some-id'] 访问tthem.

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

这篇关于当我可以在JavaScript中直接引用DOM ID时,为什么要使用document.getElementById?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆