A coworker showed me the following code and asked me why it worked.
<span id="myspan">Do you like my hat?</span>
<script type="text/javascript">
var spanElement = document.getElementById("myspan");
alert("Here I am! " + spanElement.innerHTML + "\n" + myspan.innerHTML);
</script>
I explained that a property is attached to the window object with the name of the element's id when the browser parses the document which then contains a reference to the appropriate dom node. It's sort of as if window.myspan = document.getElementById("myspan")
is called behind the scenes as the page is being rendered.
The ensuing discussion we had raised a few of questions:
The window object and most of the DOM are not part of the official JavaScript/ECMA standards, but is the above behavior documented in any other official literature, perhaps browser-related?
The above works in a browser (at least the main contenders) because there is a window object, but fails in something like rhino. Is writing code that relys on this considered bad practice because it makes too many assumptions about the execution environment?
Are there any browsers in which the above would fail, or is this considered standard behavior across the board?
Does anyone here know the answers to those questions and would be willing to enlighten me? I tried a quick internet search, but I admit I'm not sure how to even properly phrase the query. Pointers to references and documentation are welcome.
This is not a standard feature, supported only by IE and, in some cases, Opera. It may also be affected by whether the browser is in quirks mode, and whether the element has a name
attribute.
To your second point, rhino does not contain a DOM implementation itself, so the question does not apply. That is, there is no HTML interpreter built-in, so there will be no additional variables.
env.js is a DOM implementation for rhino, providing an HTML interpreter. Since IDs as window
scope variables is not a web standard, and the env project aims to be standards compliant, you will not see the described behavior there either.
Hope this helps!
来源:https://stackoverflow.com/questions/2813582/javascript-window-object-element-properties