Check If An Element Contains A Class - JavaScript Tutorial
Maybe your like
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.
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
-
How To Add A Class Name - W3Schools
-
Javascript - How To Add A Class To A Given Element? - Stack Overflow
-
JavaScript Adding A Class Name To The Element - GeeksforGeeks
-
How To Add A Class To An Element Using JavaScript - Javatpoint
-
Javascript Add Class To Div Code Example - Code Grepper
-
assList - Référence Web API | MDN
-
Add Class To Clicked Element Using JavaScript - Bobbyhadz
-
.addClass() | JQuery API Documentation
-
How To Add A Class Name To An Element With JavaScript?
-
How To Add Class Name To The HTML Element Through JavaScript?
-
Styles And Classes - The Modern JavaScript Tutorial
-
How To Add A Class To A Given Element In JavaScript
-
4 Easy Ways To Add Class To An Element Using JavaScript - Webinuse
-
JavaScript Add Class (In 3 Ways) - Tutorials Tonight