Maciej Stachowiak wrote:
For what it's worth, that's not what Gecko does, and I personally
would rather not try to enforce that -- it's somewhat expensive to do
so in the face of DOM mutations.
I tried to make some test cases to figure out the difference (in current
WebKit sources we changed to return the first match in document order to
match IE, and, we thought, Firefox)
I can describe the difference in detail if you'd like, but to a first
approximation there's a id-to-element hashtable, but it's lazily populated and
doesn't guarantee ordering. So in the following sequence of events:
1) Insert node A with id "test" into the document.
2) getElementById("test")
3) Insert node B with id "test" into the document before node A.
4) getElementById("test")
step 4 will return node A, not node B.
In all static cases (document with multiple ids loaded, then getElementById
called), you'll get the first node with that id.
<div id="foo">
</div>
<script>
alert(document.getElementById("foo"));
</script>
This is with Firefox 2.0.0.1 on Mac OS X. What am I doing wrong here?
See <https://bugzilla.mozilla.org/show_bug.cgi?id=178258>. If you put a <body>
around the whole thing you'll get the right answer. As it is, the script is
executing before the <div> has been parsed in your testcase...
-Boris