简体   繁体   中英

JavaScript getElementByName doesn't work

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

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

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

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>

此外,我发现必须声明文档类型才能使 getelementsbyname 工作。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM