JavaScript get element by name

Solution 1:

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

Solution 2:

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]

Solution 3:

You want this:

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

    alert (acc);
}

Solution 4:

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

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

Solution 5:

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

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