Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get element by name

People also ask

What is get element by name in JavaScript?

Definition and Usage. The getElementsByName() method returns a collection of elements with a specified name. The getElementsByName() method returns a live NodeList.

How do I find element by tag name?

We can find an element using the element tag name with Selenium webdriver with the help of locator tagname. To locate an element with tagname, we have to use the By. tagName method. In the above image, the text – You are browsing the best resources for has the h4 tag.

Can you get element by class in JavaScript?

The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.

What is getElementById () value?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM.


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

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]

You want this:

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

    alert (acc);
}

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

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

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

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

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