[Solved] JavaScript getElementByName doesn’t work

This simple JS can’t set the value of “para”. I guess getElementByName doesn’t work. But why?

function fn()  
    document.getElementByName("hi").setAttribute("value","my value is high");  


<input type="button" onClick="fn()" value="click me">
<input id="para" type="text" />

Solution #1:

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

Respondent: Matthew Flaschen

Solution #2:

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…

Respondent: Wrikken

Solution #3:

not getElementByName but getElementsByName, and it returns array.

    <script language="javascript">
        function fn() {
            x = document.getElementsByName("hi");
            x[0].setAttribute("value","my value is high");
<body onload="fn()">
    <input type="text" id="para" />
Respondent: Jeaf Gilbert

Solution #4:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

Respondent: Philip007

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy