In a reactive website, you would need Javascript to interact with the DOM and dynamically add, delete or change elements.

In such a case, you would have to select an element.

You can select an element by its tag but then this selection will select all the elements for that tag. So sometimes you need to assign classes to elements and then make a selection of specific classes.

Let's see how we can get an element by class using Javascript.

We have two ways in which we can get by class name, let's see each of them.


Get First Element By Class Name Using QuerySelector

If you know that there will be only one element in your DOM that has this class name, you can use the querySelector method. Incase your DOM has multiple elements matching this class name, this method will return you the first element in the node.

Syntax:


document.querySelector('.top-heading')

Example:


Get All Elements By Class Name Using QuerySelectorAll

Similar to the above method, we have a querySelectorAll method that gets all elements from the DOM matching the class name that was provided to this method.

This method returns a collection of elements that matches the class name.

Syntax:


document.querySelectorAll('.top-heading')

Example:


Get First Or Multiple Elements By Class Name Using GetElementByClassName

Another method that we can use in Javascript is the getElementByClassName method that is available to the document object.

This method takes in a string which is the class name that you want to search for.

This method returns a list of elements that matches the class name.

Syntax:


document.getElementsByClassName("class-name")

Example: