How to get elements by class name in JavaScript?

Written by Shan Shah
Updated on September 21, 2022
2 mins read
get elements by name in javascript

There are two popular and commonly used ways to get elements by class name in JavaScript. I'm going to share the examples with you.

Case:

Let's say you have ten primary links all over your HTML document with the class name link-primary, and you want to change the behavior of all the primary links. So, when someone clicks on those specific links, it should redirect the user to a specific URL.

You can select all the primary links by using getElementsByClassName or querySelectorAll. 

getElementsByClassName

Below are some quick notes for getElementsByClassName:

  • It returns the live HTMLCollection of document elements
  • You can access the elements using an index and check the number of items inside it with the length method.
  • You can not directly use any array method until you convert it into an actual array.
JavaScript get elements by name

querySelectorAll

Below are some quick notes for querySelectorAll:

  • It returns the NodeList of the document nodes
  • You can use some array methods but still need to convert it into an actual array so you can access all methods.
  • For selecting the class, you must use a period or dot before the class name.
javascript get elements by query selector all

Convert HTMLCollection or NodeList into an array

The most useful array method to convert DOM HTMLCollection or NodeList into an array is Array.from()

Just pass the array-like collection or node list through this method, and it will return a new array with the capability to use array methods.

That's it! So, in a nutshell, you learned about:

  • Two methods of getting DOM elements by class names
  • Conversion of HTMLCollection and NodeList into an array
  • Difference between querySelectorAll and getElementsByClassName

You can learn about more CSS selectors by using this CSS selectors cheatsheet.

Project Based Tutorials
Tips & Tricks
Modern Technologies
Real-World Challenges
Creative Content
Build-Apps from Scratch
Web Development Content
17+ Videos Published
Coder Champ © 2021 - 
Privacy Policy
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram