JavaScript window object element properties
- by Timothy
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.