Get Element(s) By Name In JavaScript

Last modified on August 1st, 2022
Javascript

Learn how to get one or more HTML Elements by name attribute using getElementsByName() and querySelectorAll() methods in JavaScript.

1. Get Element(s) By Name Using getElementsByName()

<button name="color">button 1</button>
<button name="color">button 2</button>
<button name="color">button 3</button>
<button name="size"> button 4</button>
<button name="color">button 5</button>

Get all the elements by name attribute color using getElementsByName() method.

const buttons = document.getElementsByName("color");
// console.log(buttons); // NodeList[4] LIVE

buttons.forEach(button => {
  button.style.background = "#32bacf"; 
})

Call the getElementsByName() on the document object.

It takes one argument which is the value of the name attribute specified in the HTML code.

In this case: color

Unlike other getElementsBy* methods, getElementsByName() method returns live NodeList.

NodeList can be iterated using in-built forEach() method.

Try it out

See the Pen Get Element(s) By Name #1 by SoftAuthor (@softauthor) on CodePen.

2. Get Element(s) By Name Using querySelectorAll()

Invoke the querySelectorAll() method on the document object.

It takes one argument but the name attribute does not have a native prefix symbol similar to id (#) or class (.) attributes.

For that reason, add the name and value of the name attribute inside square brackets separated by the equal sign in quotes.

In this case: [name=size]

const buttons = document.querySelectorAll("[name=size]");
// console.log(buttons); // NodeList[1] NOT LIVE

buttons.forEach(button => {
  button.style.background = "#32bacf"; 
})

It returns a static NodeList that has in-build forEach() method to iterate over its items.

Try it out

See the Pen Get Element(s) By Name #1 by SoftAuthor (@softauthor) on CodePen.

3. Get Element(s) By Multiple Names

To get elements by multiple names attributes in a single query, call the querySelectorAll() method on the document object passing name attributes as an argument separated by a comma in quotes.

This returns a static NodeList object that can also be iterated using forEach() method.

const buttons = document.querySelectorAll("[name=color], [name=size]");
console.log(buttons); // NodeList[5] NOT LIVE

buttons.forEach(button => {
  button.style.background = "#32bacf"; 
});

Try it out

See the Pen Get Element(s) By Name #3 by SoftAuthor (@softauthor) on CodePen.