• 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:

  • Get the Children of an Element
  • Remove a Class from an Element
  • Get the default value of a CSS property with JavaScript
  • Apply a CSS animation to an element with JavaScript

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2022 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us