In JavaScript, the document.getElementsByName() method is used to retrieve elements from the Document Object Model (DOM) based on their name attribute. This method is particularly useful when working with HTML forms where multiple elements might share the same name attribute.
• Purpose: To select elements that have a specified name attribute.
• Return Type: It returns a NodeList, which is a collection of nodes that matches the specified name.
• Usage: Ideal for accessing groups of form elements, such as radio buttons or checkboxes, which are often grouped by the same name attribute.
• Selection: The method fetches all elements that have the exact name attribute value you specify. This allows you to interact with multiple elements in a group.
• NodeList: The result is a static NodeList, meaning it does not automatically update if the DOM changes. It captures the state of the document at the time of the query.
• Applications: Commonly used in scenarios involving forms where elements are grouped under the same name for easy retrieval and manipulation.
var elements = document.getElementsByName("name");
• name: The name attribute value to search for.
<form id="myForm">
<input type="text" name="username" value="Way To Code">
<input type="text" name="email" value="info@waytocode.com">
</form>
<button onclick="showNames()">Show Usernames</button>
<script>
function showNames() {
var usernames = document.getElementsByName("username");
for (var i = 0; i < usernames.length; i++) {
document.write(usernames[i].value +
"<br>");
}
}
</script>