Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript getElementByName doesn't work

Tags:

javascript

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" />
like image 851
Philip007 Avatar asked Jun 05 '10 14:06

Philip007


4 Answers

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

like image 159
Matthew Flaschen Avatar answered Oct 29 '22 03:10

Matthew Flaschen


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

like image 44
Wrikken Avatar answered Oct 29 '22 05:10

Wrikken


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>
like image 20
Jeaf Gilbert Avatar answered Oct 29 '22 04:10

Jeaf Gilbert


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">

like image 39
Philip007 Avatar answered Oct 29 '22 05:10

Philip007