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.


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>

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

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

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

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



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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.