ArticleZip > Javascript Get Element By Name

Javascript Get Element By Name

JavaScript is a versatile and powerful programming language that is widely used in web development. When working with HTML elements on a webpage, you may sometimes need to access specific elements by their name. This is where the `getElementByName()` method comes in handy.

To use the `getElementByName()` method in JavaScript, you first need to understand that this method allows you to access elements on a webpage based on their name attribute. This can be particularly useful when you have multiple elements with the same name and you want to target a specific one.

Here's a basic example of how you can use the `getElementByName()` method:

Html

<title>Get Element By Name Example</title>


    
    <button>Get Element</button>

    
        function getElement() {
            var element = document.getElementsByName('username')[0];
            console.log(element.value);
        }

In this example, we have an input field with the name attribute set to 'username'. When the button is clicked, the `getElement()` function is called, which uses the `getElementsByName()` method to retrieve the input field with the name 'username'. We then log the value of the input field to the console.

It's important to note that the `getElementsByName()` method returns a collection of elements, even if there is only one element with the specified name. This is why we access the first element in the collection using the index `[0]` in our example.

If you need to target multiple elements with the same name, you can loop through the collection of elements returned by the `getElementsByName()` method and perform operations on each element as needed.

Here's another example that demonstrates how you can work with multiple elements with the same name:

Html

<title>Get Elements By Name Example</title>


     JavaScript
     HTML
     CSS
    <button>Get Elements</button>

    
        function getElements() {
            var elements = document.getElementsByName('language');
            elements.forEach(element =&gt; {
                if (element.checked) {
                    console.log(element.value);
                }
            });
        }

In this example, we have three checkbox elements with the name attribute set to 'language'. When the button is clicked, the `getElements()` function is called, which retrieves all elements with the name 'language' and then loop through each element to check if it's checked. If the element is checked, we log its value to the console.

In conclusion, the `getElementsByName()` method in JavaScript is a handy tool for accessing elements on a webpage based on their name attribute. Whether you need to target a single element or multiple elements with the same name, this method provides a convenient way to interact with your HTML elements dynamically.