JavaScripts getElementsByName – IE Vs Firefox

Posted by on Tue, March 20, 2007

▼ A d v e r t i s e m e n t

A little coding story. I spent quite some time to figure out what’s wrong with my code. Consider the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<html>
	<head>
	<script type="text/javascript">
	function getElements()
	{
		var x=document.getElementsByName("myInput");
		alert("First Element value is: " + x[0].value);
	}
	</script>
	</head>
 
	<body>
		<div id="myInput"></div>
		<input name="myInput" type="text" size="20" value="1" /><br />
		<input name="myInput" type="text" size="20" value="2" /><br />
		<input name="myInput" type="text" size="20" value="3" /><br />
 
		<input type="button" onclick="getElements()" value="How many elements named 'myInput'?" />
	</body>
</html>


Firefox will correctly alert you with “First Element value is: 1
IE in the other hand will alert you with “First Element value is: undefined

Why is that so? Because there exists a div with the same id myInput. In this case the JavaScript clearly uses getElementsByName. Can’t IE differentiate between Id and name?

Related Posts with Thumbnails

Tags:

Facebook Comment

WARNING & REMINDER: Comments are moderated and there is no exception. Comments unrelated to the post, too short, using phoney emails or funny names, will be marked as spam. Foul languages are filtered as spam. Your email will never be displayed on this site. If you would like to receive replies, use a valid email address and check the subscription box below.
 
  • denny

    Yes, you are right! It’s a big problem for IE to differentiate id and name. You have to be very careful when you give the id of an element so that is unique (I mean there is no other ids like this as well) for the whole document.
    Cheers

  • ady

    Thanks denny, for confirming my finding. I hope this info would be useful for others who have not encountered this problem while coding! 🙂

  • Mario

    getElementsByName is deprecated since i.e 4.0, it works only with tags a,div,iframe ans dome other but not with p, input etc..

  • ady

    @Mario: any reference to that?

  • Fredrik

    Thanks!! I have been tairing my hair out because of this js function that I just couldnt get to work in IE. I had a div id titled the same as a radio button name.

  • tlandn
  • tlandn
  • Pingback: Sketsa Web Id | Wordpress Plugin | Wordpress Theme | Web Design | | Berani Mencurangi Google Adsense?()

  • TIAGO ARAUJO SILVA

    My Solution

    var x = document.getElementById(‘teste’).getElementsByTagName(‘div’);
    //or just document.getElementsByTagName(‘div’)

    for(i=0;i<x.length;i++) { if(x[i].getAttribute(“name”)==”wanted_name”){
    //any action
    x[i].className=’invisivel’;
    }
    }