Skip to content

JavaScript get element by name Method | Example code

  • by

Use getElementsByName() method t0 get get element by name in JavaScript. This method returns a NodeList of elements. Because it’s plural in this method.

That returns an array of elements, so use [0] to get the first occurrence.

document.getElementsByName("name")[0].value

Example of How to JavaScript get element by name

If looking for a single element, take the first one from the nodelist, for example here is complete HTML code:

<!DOCTYPE html>
<html>
<body>

    Name: <input name="fname" type="text" value="John"><br>

    <button onclick="myFunction()"> Get Element</button>

    <p id="demo"></p>

    <script>
        function myFunction() {
          var x = document.getElementsByName("fname")[0].tagName;
          
          document.getElementById("demo").innerHTML = x;
      }
  </script>

</body>
</html>

Output:

JavaScript get element by name

Do comment if you have any questions or doubts or suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading