niko
niko

Reputation: 9393

IE 7 raises error when variable name is same as the element id's name

Could anyone kindly clarify this

new_pswd = $('#new_pswd').val() // does not work in ie 7 but works in all other

When I changed it to

newer_pswd = $('#new_pswd').val() // it works even in ie

I was thinking may be IE 7 does not support if the variable name is same as the element id's name ? or even other versions I don't really know because right now I have IE 7 installed on my PC.

Upvotes: 0

Views: 45

Answers (1)

acdcjunior
acdcjunior

Reputation: 135762

Having a variable equal do an element's id hold that element, as crazy as it sounds, is actually a part of HTML Standard:

6.2.4 Named access on the Window object

The Window interface supports named properties. The supported property names at any moment consist of the following, in tree order, ignoring later duplicates:

  • ...
  • the value of the id content attribute of any HTML element in the active document with a non-empty id content attribute.

Just tested here:

  • In IE7 and IE8 you can't assign a value to a variable that is an Element ID.
  • In IE 9 and Chrome you can.
  • Firefox: There are some side effects, but: version 13 only on quirks mode; version 14 and newer, standard mode.

There's are some useful discussions about this in DOM Element References as Global Variables and DOM: element IDs are global variables.

Bottom line: Don't use variable names that are elements' ids. Ultimately, it has unpredictable behaviour. If you plan on using them, please at least read those two articles.

Upvotes: 3

Related Questions