Categories
JavaScript Answers

How to Get Elements by Their name Attribute Value with JavaScript?

Spread the love

We can use the document.getElementsByName to get elements by the value of their name attribute.

For instance, if we have the following HTML:

Account <input type="text" name="acc"  value='abc'/>
Password <input type="password" name="pass" />

Then we can get the value of the first input by writing:

const [acc] = document.getElementsByName("acc")
console.log(acc.value)

We call document.getElementsByName with 'acc' to return a NodeList with all the elements that have the name attribute set to acc .

Then we destructure that to get the first element from the NodeList.

Finally, we get the value of it with acc.value .

Therefore, acc.value is 'abc' .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *