Javascript Get Element by Name

Consider this function:

function validate()
{
  var acc = document.getElementsByName('acc').value;
  var pass = document.getElementsByName('pass').value;

  alert (acc);
}

And this HTML part:

<table border="0" cellpadding="2" cellspacing="0" valign="top">
    <tr>
        <td class="td1">Account</td>
        <td class="td2"><input type="text" name="acc" /></td>
    </tr>
    <tr class="td1">
        <td>Password</td>
        <td class="td2"><input type="password" name="pass" /></td>
    </tr>
</table>
<div><button onClick="validate()" class="cupid-greenx">Login now</button></div>

The alert box is showing, but it shows "undefined".

3

7 Answers

The reason you're seeing that error is because document.getElementsByName returns a NodeList of elements. And a NodeList of elements does not have a .value property.

Use this instead:

document.getElementsByName("acc")[0].value
0

Note the plural in this method:

document.getElementsByName()

That returns an array of elements, so use [0] to get the first occurence, e.g.

document.getElementsByName()[0]
9

All Answers here seem to be outdated. Please use this now:

document.querySelector("[name='acc']");
document.querySelector("[name='pass']")

You want this:

function validate() {
    var acc = document.getElementsByName('acc')[0].value;
    var pass = document.getElementsByName('pass')[0].value;

    alert (acc);
}
3

Method document.getElementsByName returns an array of elements. You should select first, for example.

document.getElementsByName('acc')[0].value
1
document.getElementsByName("myInput")[0].value;
1

Just for completeness so others reading this have a good idea of safety nets, especially with no guarantee to get the element you want, you could test for missing values, using null coalesce to set a default:

const accElements = document.getElementsByName('acc');
const accElement = accElements[0] ?? null; // Or some other value
if (!accElement) {
    // handle the problem
}

And use Optional chaining when it's connected objects (and not arrays/nodes being returned):

const acc = document.getElementById('acc')?.value ?? null; // Or some other value

Also, while the name attribute is sometimes all that is available, do try to use id where possible as they have more chance of being unique. Assuming that your desired element is in results index 0 ([0]) is usually safe, but better to check and be sure. For a few lines of code (with some logging perhaps) you save your end users the problems of things breaking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest