Check whether an element exists with a given class in JavaScript/jQuery
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
|
1 2 3 4 5 6 7 8 |
$(document).ready(function() { if ($('div').hasClass('container')) { alert('Class exists'); } else { alert('Class does not exist'); } }); |
HTML
|
1 |
<div class="container"></div> |
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
|
1 2 3 4 5 6 7 8 |
$(document).ready(function() { if ($('div.container')[0]) { alert('Class exists'); } else { alert('Class does not exist'); } }); |
HTML
|
1 |
<div class="container"></div> |
Alternatively, you can check the length of the jQuery object returned by the class selector for better readability.
JS
|
1 2 3 4 5 6 7 8 |
$(document).ready(function() { if ($('div.container').length) { alert('Class exists'); } else { alert('Class does not exist'); } }); |
HTML
|
1 |
<div class="container"></div> |
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
|
1 2 3 4 5 6 |
if (document.getElementsByClassName('container').length) { alert('Class exists'); } else { alert('Class does not exist'); } |
HTML
|
1 |
<div class="container"></div> |
To target an element with its ID, use the querySelector() function.
JS
|
1 2 3 4 5 6 |
if (document.querySelector('div.container') !== null) { alert('Class exists'); } else { alert('Class does not exist'); } |
HTML
|
1 |
<div class="container"></div> |
Another plausible way is to use the classList property with getElementById() function.
JS
|
1 2 3 4 5 6 7 |
var div = document.getElementById('outerdiv'); if (div.classList.contains('container')) { alert('Class exists'); } else { alert('Class does not exist'); } |
HTML
|
1 |
<div id="outerdiv" class="container"></div> |
That’s all about determining whether an element exists with a given class in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)