JavaScripts getElementsByName – IE Vs Firefox

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?

0 Shares

9 thoughts on “JavaScripts getElementsByName – IE Vs Firefox”

  1. 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

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

  3. 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..

  4. 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.

  5. 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’;
    }
    }

Comments are closed.