getElementsByName Method
In this tutorial, we will learn about the getElementsByName method in JavaScript.
In JavaScript, the getElementsByName() method is used to get a collection of elements with the specified name attribute from the document. It is a method of the document object that allows you to access and manipulate elements in the HTML document by their name attribute.
Syntax
The syntax for the getElementsByName() method is as follows:
let elements = document.getElementsByName(name);Where:
nameis a string that specifies the name attribute of the elements you want to get.elementsis a collection of elements with the specified name attribute.
Example
Suppose you have the following HTML document:
<!doctype html>
<html>
<head>
<title>Get Elements By Name Example</title>
</head>
<body>
<input type="text" name="myName" value="" />
<input type="text" name="myName" value="" />
<input type="text" name="myName" value="" />
<script src="script.js"></script>
</body>
</html>You can use the getElementsByName() method to get all input elements with the name attribute email and change their values:
let elements = document.getElementsByName("myName");
for (let i = 0; i < elements.length; i++) {
elements[i].value = "This is my new value";
}This will change the value of all input elements with the name attribute myName to This is my new value.
Conclusion
- The
getElementsByName()method allows you to get a collection of elements with the specified name attribute from the document. - You can use the
getElementsByName()method to access and manipulate elements in the HTML document by their name attribute. - The
getElementsByName()method returns a collection of elements with the specified name attribute as an array-like object. - You can use the
getElementsByName()method to get a collection of elements with the same name attribute and perform operations on them.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on