The JavaScript .getElementsByName() method allows you to select and access HTML elements based on their name attribute. It returns a collection of all the elements with the specified name in the document. Here is a detailed explanation along with examples of different use cases:
document.getElementsByName(name)
name: A string value representing the name attribute of the elements you want to select.
Return value: A collection of elements with the specified name. It typically returns an array-like object called a NodeList, which can be accessed using array-like notation or converted to an actual array using Array.from() or the spread syntax.
The following are some examples on how to use getElementsByName():
Example 1: Selecting Elements by Name
HTML:
<input type="text" name="username" />
<input type="password" name="password" />
<input type="checkbox" name="interest" value="coding" />
<input type="checkbox" name="interest" value="gaming" />
JavaScript:
const usernameInputs = document.getElementsByName('username');
console.log(usernameInputs); // NodeList containing the "username" input element
const interestInputs = document.getElementsByName('interest');
console.log(interestInputs); // NodeList containing both "interest" input elements
In this example, .getElementsByName() is used to select multiple input elements with the name attributes "username" and "interest".
Example 2: Accessing Elements by Index
HTML:
<input type="text" name="username" />
<input type="text" name="username" />
<input type="text" name="username" />
JavaScript:
const usernameInputs = document.getElementsByName('username');
console.log(usernameInputs[0].value); // Value of the first element
console.log(usernameInputs[1].value); // Value of the second element
console.log(usernameInputs[2].value); // Value of the third element
In this example, .getElementsByName() returns a NodeList of input elements with the name attribute "username". You can access each element using array-like notation with an index, similar to accessing elements in an array.
Example 3: Modifying Elements with a Loop
HTML:
<input type="checkbox" name="interest" value="coding" />
<input type="checkbox" name="interest" value="gaming" />
JavaScript:
const interestInputs = document.getElementsByName('interest');
for(let i = 0; i < interestInputs.length; i++) {
interestInputs[i].checked = true;
}
In this example, .getElementsByName() is used to select the input elements with the name attribute "interest". A for loop iterates over each element and sets the checked property to true. This code ensures that all checkboxes with that name attribute are checked.
getElementsByName() is case-sensitive. It selects elements based on their name attribute, not the label or ID. If you want more specialized or specific element selection, consider using methods like .querySelectorAll() or .getElementById().