Get an Element by Name attribute using JavaScript

JavaScript get elemtnt by name example; In this tutorial you will learn how to Get an Element by Name attribute using JavaScript.

The getElementsByName() method returns a collection of elements with a specified name. The getElementsByName() method returns a collection of all elements in the document with the specified name (the value of the name attribute), as an HTMLCollection object.

Whenever we need to get the elements by name of input box, textarea, radio button, select box or checkbox etc. Mostly select checkbox or radio and get value by name is more required any times.

JavaScript getElementsByName() method

var element = document.getElementsByName("name");
  • elements is a live NodeList Collection, meaning it automatically updates as new elements with the same name are added to/removed from the document.
  • name is the value of the name attribute of the element(s).

JavaScript get Element By Name example

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    </head>
    <body>
        <div class="container">
           <div class="row">
               <div class="col-12">
                   <input class="form-control" type="text" name="amount" value="5">
               </div>
           </div>
        </div>
        <script>
            let element = document.getElementsByName('amount');
            console.log(element[0].value);
        </script>
    </body>
</html>

Unlike the id attribute, multiple HTML elements can share the same value of the name attribute like this:

Javascript get Checkbox Value by Name Example

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    </head>
    <body>
        <div class="container">
           <div class="row">
               <div class="col-12">
                   Cricket:  <input name="hobby" type="checkbox" value="Cricket">
                   Football:  <input name="hobby" type="checkbox" value="Football">
                   <button onclick="getValue()">Get Value</button>
               </div>
           </div>
        </div>
        <script>
            function getValue() {
              var elements = document.getElementsByName("hobby");
              for (var i = 0; i < elements.length; i++) {
                  console.log(elements[i].value);
                if (elements[i].type == "checkbox") {
                  elements[i].checked = true;
                }
              }
            }
        </script>
    </body>
</html>

Javascript get Radio Value by Name Example

The HTMLCollection object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JavaScript getElementsByName Demo</title>
</head>
<body>
    <p>Please rate the service:</p>
    <p>
        <input type="radio" name="rate" value="Very poor"> Very poor
        <input type="radio" name="rate" value="Poor"> Poor
        <input type="radio" name="rate" value="OK"> OK
        <input type="radio" name="rate" value="Good"> Good
        <input type="radio" name="rate" value="Very Good"> Very Good
    </p>
    <p>
        <button id="btnRate">Submit</button>
    </p>
    <script>
        let btn = document.getElementById('btnRate');

        btn.addEventListener('click', () => {
            let rates = document.getElementsByName('rate');
            rates.forEach((rate) => {
                if (rate.checked) {
                    alert(`You rated: ${rate.value}`);
                }
            })
        });
    </script>
</body>
</html>
  • The getElementsByName() returns a live NodeList of elements with a specified name.
  • The NodeList is an array-like object, not an array object.

Leave a Comment