开发者

Referring to HTML elements in Javascript by just their ID

Apparently the ids for HTML elements get loaded into the global namespace for Javascript on an HTML page. As such, if I have HTML like:

<p id="mypara">Hello</p>

I can run Javascript like:

mypara.innerText += " world";

which results in the paragraph having "Hello world" as its text in IE9 and Chrome on Windows. This seems like a more convenient way to refer to HTML elements than the standard

document.getElementById("mypara").innerText += " world";

As far as I can tell, the cons seem to be that you can't give HTML elements ids that are Javascript keywords (doesn't seem so bad) and your global namespace is more polluted.

Are there any other problems with this approach? Is there any documentation that describes exactly when/how the population of the global namespace is done by browsers? Are there quirks or pitfall开发者_开发问答s? Has anyone done any browser compatibility testing?


Early IE introduced the practice of making element ids and names global references to the elements. It was never standardised and was considered a very bad idea.

Other browsers provided various levels of support for the practice to be compatible with sites written for IE, but generally support was minimal (even hidden to some extent) to discourage its use. Some browsers only supported it in quirks mode or with certain DOCTYPEs.

It is still considered a very bad idea, do not use it. Use appropriate DOM methods, don't rely on such browser quirks.


I would worry about the script working in older browsers. For example this fiddle does not work in Firefox 3.

http://jsfiddle.net/rrSwW/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜