News for hackers. Stuff that matters.
Re:Nine Javascript Gotchas by axod on Thursday February 14, 2008 @05:06PM (#116113)
The reason that code works is because in IE you're not actually doing anything. All elements with IDs are already in the global scope.

var bob = $('bob'); is a useless statement in IE.

The issue comes when you do something more like this.

<script> var bob = "hello world"; </script> <div id="bob">Hi</div>

now bob doesn't equal "hello world". Your global has been clobbered.

---

Similarly, it's surprising how many people fall into this trap:

<input type=submit id=submit>

Well that's all great and everything, but you've just clobbered the submit() function on the form.

before:

form.submit = function()

now:

form.submit = Your dumb input element.

Re:Nine Javascript Gotchas by gruseom on Thursday February 14, 2008 @05:47PM (#116136)
This explanation makes sense, but I can't reproduce the behavior.

in IE ... all elements with IDs are already in the global scope

This I can confirm. If the page contains this:

  <div id="bob">Hi</div>
then the following evaluates to true in IE:

  bob == $("bob")
...without defining the variable. I didn't know that - thanks!

The issue comes when you do something more like this.

  <script> var bob = "hello world"; </script> <div id="bob">Hi</div>
now bob doesn't equal "hello world". Your global has been clobbered.

One might expect this, given the above, but I tried it in both IE6 and IE7 and the global keeps the value it had before.

Re:Nine Javascript Gotchas by axod on Thursday February 14, 2008 @06:04PM (#116144)
OK It's been a while. It may only happen when you start modifying the dom, or using innerHTML.

End of the day though it's a bad idea and at some point you'll clobber variables you didn't want to.