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.