This post will discuss how to check whether an element exists with a given class in JavaScript and jQuery.

1. Using jQuery

The jQuery’s .hasClass() method returns true if the specified class is assigned to an element. For example, the following will return true if the div contains container as a class.

JS


HTML



Edit in JSFiddle

 
Another solution is to use the class selector, which selects all elements with the given class. The following program finds an element with the class container, which returns a falsy value at the first index when class is not found.

JS


HTML



Edit in JSFiddle

 
Alternatively, you can check the length of the jQuery object returned by the class selector for better readability.

JS


HTML



Edit in JSFiddle

2. Using JavaScript

With JavaScript, you can use JavaScript’s native getElementsByClassName() function. However, this determines if a class exists or not but does not identify the element linked to the class.

JS


HTML



Edit in JSFiddle

 
To target an element with its ID, use the querySelector() function.

JS


HTML



Edit in JSFiddle

 
Another plausible way is to use the classList property with getElementById() function.

JS


HTML



Edit in JSFiddle

That’s all about determining whether an element exists with a given class in JavaScript and jQuery.