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.
Below are some quick notes for getElementsByClassName:
Below are some quick notes for querySelectorAll:
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:
You can learn about more CSS selectors by using this CSS selectors cheatsheet.