This post will discuss how to get elements by class name using JavaScript and jQuery.

1. Using jQuery – Class Selector

In jQuery, you can use the class selector ('.class') to select all elements with the given class.

$()


CSS


HTML



Edit in JSFiddle

 
Note that we can apply the same class to multiple elements within the document. So, it is advisable to fetch an element by its id.

2. Using JavaScript – getElementsByClassName() function

In pure JavaScript, you can use the native getElementsByClassName() method, which returns the NodeList of all elements having the given class.

JS


CSS


HTML



Edit in JSFiddle

3. Using JavaScript – querySelector() function

The querySelectorAll() method returns all elements within the document having the same class. To get the first element that matches the specified selector, you can use the querySelector() method.

JS


CSS


HTML



Edit in JSFiddle

That’s all about getting element by class name using JavaScript and jQuery.