No it won't. I do this all the time; it works fine in IE 6 and 7.
No it won't. I do this all the time; it works fine in IE 6 and 7.
Untested, but it may also have to do with globally defined variables.
<div id="bob">...</div>
<script>var bob = $('bob');</script>
Seems almost identical to the code in the post (mine says "var" and his doesn't, mine uses $ to get element by id, his uses a 'get' function that presumably does the same thing). It does not produce an 'object undefined' error (or any error that I've seen).By "it works fine" I mean that the variable bob references the appropriate DOM element and behaves as expected.
What should I change in the above to reproduce this error?
and is called global namespace polluting. and it could get things mixed up. So, a good practise is not to name DOM elements with javascript variables.
The reason you never ran into the problem is because that locally you create a variable with a reference to the DOM element, so you are practising a "workaround"
If you want an element by ID, that's what document.getElementByID is for (or $ if you're using a JS framework). If you want a form element by its name (why not it's id?), you should go out to get that specifically.
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.
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.
End of the day though it's a bad idea and at some point you'll clobber variables you didn't want to.