admin管理员组文章数量:1357273
I have:
<div id="myDiv1"></div>
<div id="myDiv2"></div>
In JavaScript, I can set div innerHTML by writing:
myDiv1.innerHTML = "myDiv1, Hi!"
or
document.getElementById("myDiv2").innerHTML = "myDiv2, Hi!"
Why should I use document.getElementById when I can simply use element Id ? Is this working every time or only in some special scenarios (like simple sample)?
thanks,
Mike
I have:
<div id="myDiv1"></div>
<div id="myDiv2"></div>
In JavaScript, I can set div innerHTML by writing:
myDiv1.innerHTML = "myDiv1, Hi!"
or
document.getElementById("myDiv2").innerHTML = "myDiv2, Hi!"
Why should I use document.getElementById when I can simply use element Id ? Is this working every time or only in some special scenarios (like simple sample)?
thanks,
Mike
Share Improve this question edited Feb 5, 2015 at 10:06 T.J. Crowder 1.1m200 gold badges2k silver badges1.9k bronze badges asked Feb 5, 2015 at 10:00 mike mmike m 1351 silver badge9 bronze badges 5-
In your first snippet, you are using
myDiv1
. How have you retrieved it? – Giorgio Commented Feb 5, 2015 at 10:03 - 1 No, you can't. Just you can assign to var every one div by ID, but nothing without this assignment. – pavel Commented Feb 5, 2015 at 10:03
- 1 This does work, but it's a bad idea. – lonesomeday Commented Feb 5, 2015 at 10:04
- It is true that browsers expose elements with ids as global variables. But this is not reliable and error prone, as any globals in general. Plus there is no guarantee that older browsers will do the same. – dfsq Commented Feb 5, 2015 at 10:04
-
@Giorgio: It's an automatic global, because the element has an
id
. – T.J. Crowder Commented Feb 5, 2015 at 10:04
2 Answers
Reset to default 8Why should I use document.getElementById when I can simply use element Id ?
To avoid conflicts. The global namespace on browsers is incredibly crowded, all sorts of things are dumped in there, including (as you've found) globals referring to any element with an id
(so-called "automatic globals").
In contrast, getElementById
only does what it says, finds an element by its id
; it's more constrained. (Other than bugs in old versions of IE, which also looked at elements with name
attributes.)
when you write
myDiv1.innerHTML = "myDiv1, Hi!"
you are calling window object, so actual call is like this
window.myDiv1.innerHTML = "myDiv1, Hi!"
This behavior is deprecated now and to be avoided. Instead we should use
document.getElementById`
本文标签: domJavaScript documentgetElementById(“id”) and element id attributeStack Overflow
版权声明:本文标题:dom - JavaScript document.getElementById(“id”) and element id attribute - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743953667a2567747.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论