Checking if an element has a class in JavaScript involves using the classList property, which provides methods to interact with CSS classes on DOM elements.
CSS classes are used to style HTML elements by applying predefined styles. Classes are defined using the class attribute in HTML, and one or more classes can be assigned to an element, separated by spaces.
For example, the following HTML element has two classes, “red” and “bold”:
<p class="red bold">This is a paragraph</p>
The classList
property is available on DOM elements and provides methods to add, remove, toggle, and check for the presence of CSS classes on an element.
The classList
property is supported in modern browsers and is a convenient way to manipulate classes in JavaScript.
Using classList.contains()
to check for a class:
The classList.contains()
method is used to check if an element has a specific class.
It takes a class name as an argument and returns true if the class is present on the element, and false otherwise.
For example:
// Get the DOM element
var element = document.getElementById("myElement");
// Check if the element has a class
if (element.classList.contains("myClass")) {
console.log('Element has the class "myClass"');
} else {
console.log('Element does not have the class "myClass"');
}
In the above example, myElement
is the DOM element you want to check for the presence of the class "myClass"
. The classList.contains()
method is used to check if the element has the specified class, and it returns true
if the class is present and false
if it is not.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.