Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to get the elements by their name attribute value with JavaScript.

In this article, we’ll look at how to get the elements by their name attribute value with JavaScript.

Use the document.getElementsByName Method

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' .

Conclusion

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

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 *