How to get elements by class name in JavaScript?

How to get elements by class 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 class 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.

Our Coding guides: 

Leave a comment

All comments are moderated before being published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.