How to get element by class name in JavaScript?

Getting an element using JavaScript is the very first thing we do when we start manipulating DOM using JavaScript. Using JavaScript we can interact with DOM very effectively and efficiently.

There are a couple of different ways to get an element object using JavaScript. Following section, we have explained different approaches to getting elements from DOM using JavaScript:

Using document.querySelector:

document.querySelector(".class_name")

The above line will get the first element with the above selector(class_name). NULL will be returned if none of the elements on the document has the above class.

Using document. getElementsByClassName

document.getElementsByClassName("class_name")

The above line will get an array of elements with the above selector(class_name). An empty HTMLCollection will be returned if none of the elements on the document has the above class.

If we need to get the first element matches with the above class, we can do the following:

document.getElementsByClassName('class_name')[0]

Using document.querySelectorAll:

document.querySelectorAll(".class_name")

The above line will get an array of elements with the above selector(class_name). An empty NodeList will be returned if none of the elements on the document has the above class.

If we need to get the first element matches with the above class, we can do the following:

document.querySelectorAll(".class_name")[0]