Connecting Tech Pros Worldwide Forums | Help | Site Map

Browser Bug: document.getElementById() gets the wrong element (IE)

acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#1   Aug 18 '07
Problem
document.getElementById() selects an element by its name.

Browser
Internet Explorer

Example
Relevant HTML code:
[HTML]<input name="test" type="text" value="test">[/HTML]
The Javascript code:
Expand|Select|Wrap|Line Numbers
  1. var obj = document.getElementById("test");
This will not result in an error and the element is available as 'obj' even though no element with the id "test" exists on the page.

Solution
This is a bug which will cause problems in most, if not all, other browsers. document.getElementById() should get an element by its ID as the name suggests, not by its name. This will also cause problems in IE when you have an element with a name the same as the ID of the element you actually want to access. The wrong element will be accessed!

Be careful how you name your elements. Do not use the same name as the ID of another element.

More Bugs, Quirks and Inconsistencies



Reply


Similar JavaScript / Ajax / DHTML bytes