JavaScript is a powerful programming language that is widely used for creating interactive and dynamic web pages. One of the key features of JavaScript is its ability to manipulate the Document Object Model (DOM), which represents the structure of an HTML document.
The document.getElementsByName()
method is a useful function in JavaScript that allows you to retrieve a collection of elements in the DOM based on their name attribute. This method returns a NodeList object, which is similar to an array, containing all the elements that match the specified name attribute.
Here is the syntax of the document.getElementsByName()
method:
var elements = document.getElementsByName(name);
Let’s take a closer look at how this method works with some examples:
Example 1: Retrieving Radio Buttons with the Same Name
Suppose you have a form with multiple radio buttons that share the same name attribute. You can use the document.getElementsByName()
method to select all the radio buttons with that name and perform operations on them.
<form>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="other"> Other
</form>
<script>
var genderRadios = document.getElementsByName("gender");
for (var i = 0; i < genderRadios.length; i++) {
console.log(genderRadios[i].value);
}
</script>
In this example, the document.getElementsByName("gender")
statement selects all the radio buttons with the name attribute set to “gender”. The for loop then iterates through the collection and logs the value of each radio button to the console.
Example 2: Changing the Style of Elements with the Same Name
Another common use case for the document.getElementsByName()
method is when you want to modify the style of multiple elements with the same name. You can access individual elements in the NodeList returned by the method and apply CSS properties to them.
<style>
.highlight {
background-color: yellow;
}
</style>
<ul>
<li name="item">Item 1</li>
<li name="item">Item 2</li>
<li name="item">Item 3</li>
</ul>
<script>
var items = document.getElementsByName("item");
for (var i = 0; i < items.length; i++) {
items[i].classList.add("highlight");
}
</script>
In this example, the CSS class “highlight” is defined to set the background color to yellow. The document.getElementsByName("item")
statement selects all the list items with the name attribute set to “item”. The for loop then adds the “highlight” class to each list item, resulting in a yellow background color for all the items.
The document.getElementsByName()
method is a powerful tool in JavaScript for selecting and manipulating elements based on their name attribute. It provides a convenient way to work with collections of elements and perform actions on them.
Remember to use this method judiciously and ensure that the name attribute is used appropriately in your HTML markup to avoid any confusion or conflicts in your JavaScript code.