22

This simple JS can't set the value of "para". I guess getElementByName doesn't work. But why?

<script>
function fn()  
{   
    document.getElementById("para").setAttribute("name","hi");  
    document.getElementByName("hi").setAttribute("value","my value is high");  
}  
</script>

HTML:

<input type="button" onClick="fn()" value="click me">
<input id="para" type="text" />
Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
Philip007
  • 3,190
  • 7
  • 46
  • 71
  • possible duplicate of [getElementsByName in IE7](http://stackoverflow.com/questions/278719/getelementsbyname-in-ie7) – John K Jun 05 '10 at 15:05
  • See answer here http://stackoverflow.com/questions/278719/getelementsbyname-in-ie7 – John K Jun 05 '10 at 15:04

4 Answers4

53

It's getElementsByName . Note the plural. It returns an array-like NodeList of elements with that name attribute.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
19

getElementsByName exists, which returns a collection of the elements. If you plan to find only one:

document.getElementsByName("hi")[0].setAttribute("value", "my value is high");

Edit: a, HTML there (didn't see that before the edit). No 'hi' element in HTML, possibly in some XML format there is...

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Wrikken
  • 69,272
  • 8
  • 97
  • 136
2

not getElementByName but getElementsByName, and it returns array.

<html>
<head>
    <script language="javascript">
        function fn() {
            document.getElementById("para").setAttribute("name","hi");
            x = document.getElementsByName("hi");
            x[0].setAttribute("value","my value is high");
        }
    </script>
</head>
<body onload="fn()">
    <input type="text" id="para" />
</body>
</html>
Jeaf Gilbert
  • 11,495
  • 19
  • 78
  • 105
1

Also, i find that document type must be declared to make getelementsbyname work.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Philip007
  • 3,190
  • 7
  • 46
  • 71