In this tutorial we will learn how to Check If HTML Element of particular Class Exists using JavaScript. HTML DOM getElementsByClassName() method and .length property can be used for this purpose.
Table of Contents
HTML Code
HTML Code is given below, in this code we have a paragraph tag with class red, we also have a button tag with onclick event.
<p class="red" id='text'>My Class is Red</p>
<button onclick="checkClass()">Check Class</button>
JavaScript Code
Take a look at the JavaScript code, the HTML Dom getElementsByClassName() method is used with .length property.
HTML Dom getElementsByClassName() is used to select all HTML elements with particular class.
.length property returns the length of a string. In this example it is used to count the number of selected elements with defined class (red).
If answer of elements.length is greater than 0, it means the class exist.
<script>
function checkClass()
{
var elements = document.getElementsByClassName('red');
if (elements.length > 0)
{
alert("class exist");
}
else
{
alert("class doesn't exist");
}
}
</script>
Another way to check this is by using the following code.
<script>
function checkClass()
{
var element = document.getElementById('text');
if (element.classList.contains('red'))
{
alert("class existsdd");
}
else
{
alert("class doesn't exist");
}
}
</script>
In above code .classList property is used which is used to return the class names as object.
.contains is used to check the class in the classList object. The answer of .contains is a Boolean value.
Demo
Video Tutorial
Watch video tutorial on How To Check If Class Exists in JavaScript.