• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / CSS / Check If an Element contains a Class

Check If an Element contains a Class

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);

Suppose you have the following <div> element:

<div class="secondary info">Item</div>

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

const div = document.querySelector('.info');
div.classList.contains('secondary'); // true

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

const div = document.querySelector('.info');
div.classList.contains('error'); // false

Source

https://www.javascripttutorial.net/dom/css/check-if-an-element-contains-a-class/

CSS

Related Snippets:

  • Resize the width of a text box to fit its content automatically
  • Selecting Elements By Class Name
  • Add, remove, toggle, and check for the presence of a class
  • Create a custom scrollbar

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers