Get HTML element by Name

In javascript, getElementsByName() method is useful to access the HTML elements using the name. Here, the name suggests the name attribute of the HTML element. This method returns the collection of HTML elements that includes the particular name. Users can get the length of the collection using the build-in length method.

Syntax:

document.getElementsByName(element_name);

Parameter:

It takes the name of the element which the user wants to access.

Return value:

It returns the collection of elements that have a particular name.

Example: This example demonstrates the use of the getElementsByName method. It prints every element with a particular name into the console. Users can open the console in the Chrome web browser by pressing ctrl + shift + I.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
 
<body>
    <!-- Multiple html element with w3wiki name -->
    <h1 name="w3wiki">w3wiki sample 1</h1>
    <h1 name="w3wiki">w3wiki sample 2</h1>
    <h1 name="w3wiki">w3wiki sample 3</h1>
 
    <p>DOM getElementsByName() Method</p>
    <script>
 
        // Accessing the element by getElementsByName method
        let temp = document.getElementsByName("w3wiki");
        console.log(temp[0]);
        console.log(temp[1]);
        console.log(temp[2]);
    </script>
</body>
</html>


Output:

Different ways to access HTML elements using JavaScript

Sometimes, users need to manipulate the HTML element without changing the code of the HTML. In this scenario, users can use JavaScript to change HTML elements without overwriting them. Before we move ahead to change the HTML element using JavaScript, users should learn to access it from the DOM (Document Object Model). Here, the DOM is the structure of the web page. 

From the DOM, users can access HTML elements in five different ways in JavaScript:

Table of Content

  • Get HTML element by Id
  • Get HTML element by className
  • Get HTML element by Name
  • Get HTML elements by TagName
  • Get HTML elements by CSS Selector

Similar Reads

Get HTML element by Id

Generally, most developers use unique ids in the whole HTML document. The user has to add the id to the particular HTML element before accessing the HTML element with the id. Users can use getElementById() method to access the HTML element using the id. If any element doesn’t exist with the passed id into the getElementById method, it returns the null value....

Get HTML element by className

...

Get HTML element by Name

In javascript, the getElementsByClassName() method is useful to access the HTML elements using the className. The developers can use a single className multiple times in a particular HTML document. When users try to access an element using the className, it returns the collection of all objects that include a particular class....

Get HTML elements by TagName

...

Get HTML elements by CSS Selector

...