The getElementsByName method is used to access HTML elements based on their "name" attribute.
This method returns a live NodeList, which is a collection of nodes similar to an array, containing all elements with the specified name attribute.
<script> var elements = document.getElementsByName('value associated with name attribute in element'); </script>
value: It specifies the `value associated with name attribute in element` in the DOM, which we can access to fetch information or modify content.
Return value: If an element with the specified ID exists in the document (DOM), the `getElementsByName` function returns a reference to that element. Otherwise, it returns null.
Here, we have created HTML elements, added `name` attributes, and initialized values.
<input type="text" name="username" placeholder="Enter your username"> <input type="password" name="password" placeholder="Enter your password"> <button type="button" onclick="displayValues()">Submit</button>
Here, in Script we have added the Script tag and added `getElementsByName` function.
<script> function displayValues() { // Accessing elements with the name attribute 'username' var usernameElements = document.getElementsByName('username'); // Accessing elements with the name attribute 'password' var passwordElements = document.getElementsByName('password'); // Displaying the values in an alert alert('Username: ' + usernameElements[0].value + '\nPassword: ' + passwordElements[0].value); } </script>
In the example, we have raised an alert prompt on button click and it will display the values in the alert prompt.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>getElementsByName Example</title> </head> <body> <form> <input type="text" name="username" placeholder="Enter your username"> <input type="password" name="password" placeholder="Enter your password"> <button type="button" onclick="displayValues()">Submit</button> </form> <script> function displayValues() { // Accessing elements with the name attribute 'username' var usernameElements = document.getElementsByName('username'); // Accessing elements with the name attribute 'password' var passwordElements = document.getElementsByName('password'); // Displaying the values in an alert alert('Username: ' + usernameElements[0].value + '\nPassword: ' + passwordElements[0].value); } </script> </body> </html>
The `getElementsByName` method obtains a live NodeList containing all elements with the name attribute 'username' and 'password'.
The script then displays the values of these elements in an alert when the "Submit" button is clicked.