Check If An Element Contains A Class - JavaScript Tutorial

Skip to content

Home » Check If an Element contains a Class

To check if an element contains a class, you use the contains() method of the classList property of the element:

element.classList.contains(className);Code language: CSS (css)

In this method, you pass the className to the contains() method of the classList property of the element. If the element contains the className, the method returns true. Otherwise, it returns false.

For example, suppose you have the following <div> element with two classes: secondary and info:

<div class="secondary info">Item</div>Code language: HTML, XML (xml)

To check if the <div> element contains the secondary class, you use the following code:

const div = document.querySelector('div'); div.classList.contains('secondary'); // trueCode language: JavaScript (javascript)

In this example, we use the querySelector() method to select the div and use the contains() method to check if its class list contains the secondary class.

The following example returns false because the <div> element doesn’t have the error class:

const div = document.querySelector('div'); div.classList.contains('error'); // falseCode language: JavaScript (javascript)

Summary

  • Use the element.classList.contains() method to check if an element contains a specific class name.
Send Cancel Toggle a Class of an ElementPreviouslyToggle a Class of an Element Up NextReplace a Class of an Element Replace a Class of an Element Search for:

Getting Started

JavaScript Fundamentals

JavaScript Operators

Control Flow

JavaScript Functions

JavaScript Objects

Classes

Advanced Functions

Promises & Async/Await

JavaScript Modules

Javascript Error Handling

JavaScript Runtime

Primitive Wrapper Types

More JavaScript Operators

Tag » Add Classname To Div Javascript