Document.getElementById() returns element with name equal to id specified

非 Y 不嫁゛ 提交于 2019-12-01 04:06:57

问题


I have previously mentioned in this SO about the funny behavior for IE6/7 (and some versions of Opera) in that document.getElementById can find an element whose name attribute is defined but not the id attribute, such that

function f() {
    document.getElementById("a1").value = ...;
}
...
<input name="a1" ...></input>

actually works in these versions.

Searching through the net I found this bug report by Chris Bloom, in which a user named Milo van der Leij points out the following (as referred by him in this w3c spec):

In their defense: "The id and name attributes share the same name space."

What does it mean that the id and name attributes share the same namespace? Why would this condition be sufficient for IE6/7/Opera implement this behavior in their JS engine?


回答1:


The term "same namespace" means that names and ids are not completely separate. You can use the same name and id on one particular object, but you cannot use name="foo" on one object and id="foo" on another object. That creates a conflict.

It's just the way those browsers decided to implement things. There's also a global variable for each element with an id that contains the dom element. That's just the way they implemented things. It wasn't standard, it isn't the way things are done in more modern browsers (except for some backward compatibility).

Use id values for any DOM elements you want to retrieve. Use name values for server identification in posted forms.

Your code will have no conflicts between names and ids if you don't use an id on one object and the same name on another object, and there generally isn't an issue with giving a particular element the same name and id.



来源:https://stackoverflow.com/questions/13300698/document-getelementbyid-returns-element-with-name-equal-to-id-specified

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