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?