最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - JavaScript document.getElementById(“id”) and element id attribute - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 8

Why 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` 
发布评论

评论列表(0)

  1. 暂无评论