What is document.getElementByName() in JavaScript?

The getElementByName() method will help you find all elements in DOM whose name attribute is the same.

Syntax

var element = document.getElementByName('First_Name');

Parameter

A single parameter of type string is needed, which is the name given to that element or tag in HTML.

Return value

getElementByName() returns an HTML Collection object which represents a collection of elements with same name. The index is used to access the elements from the object.

Code

Let’s try to use the getElementByName() method to change the behavior of DOM elements.

The task is to highlight the names of animals from the list which has names of places, animals, and others.

Check the following code:

Console

Explanation

The example above has an HTML code that has a paragraph tag with the name attribute of place or animal, and a button tag with a function (myFuction()) which will be called when the button is clicked.

In the JavaScript code:

  • In line 1, myFunction() is created to run after we click on the button.

  • In line 2, we store all the elements from DOM with name equals to animal in variable x.

  • In line 5, we iterate over x and access elements through indexes.

  • In line 7, we change the color and highlight the text using the property style.color.

Free Resources