Sometimes, we want to get elements by name with JavaScript.
In this article, we’ll look at how to get elements by name with JavaScript.
How to get elements by name with JavaScript?
To get elements by name with JavaScript, we use the getElementsByName
method.
For instance, we write
<input type="text" name="acc" /> <input type="password" name="pass" /><
to add 2 inputs.
Then we write
const value = document.getElementsByName("acc")[0].value;
to get all elements with name
attribute acc
with getElementsByName
.
We get the first element with the name
attribute value with [0]
.
And we get its value with value
.
Conclusion
To get elements by name with JavaScript, we use the getElementsByName
method.