Skip to content

hasClass

Jason Godesky edited this page Mar 31, 2024 · 3 revisions

This function returns true if an HTMLElement object has any of the classes given, or false if it does not.

Parameters

el
This is the HTMLElement object being inspected.
classes
The class or classes you would like to check the HTMLElement object for. As of v0.2.4, this can include strings and/or `null` values. The `null` values are filtered out, but this allows you to use ternary operators in the same array where you define your classes for conditional classes, without extra filtering operations.

Examples

In each of the examples below, let’s assume that you have a body like this:

<body>
  <div id="example1"></div>
  <div id="example2" class="foo"></div>
  <div id="example3" class="bar"></div>
  <div id="example4" class="foo bar"></div>
</body>

Checking for one class

import { hasClass } from 'unobtrusive-dom'

hasClass(document.getElementById('example1'), 'foo') // false
hasClass(document.getElementById('example2'), 'foo') // true
hasClass(document.getElementById('example3'), 'foo') // false
hasClass(document.getElementById('example4'), 'foo') // true

Checking for two classes

import { hasClass } from 'unobtrusive-dom'

hasClass(document.getElementById('example1'), 'foo', 'bar') // false
hasClass(document.getElementById('example2'), 'foo', 'bar') // true
hasClass(document.getElementById('example3'), 'foo', 'bar') // true
hasClass(document.getElementById('example4'), 'foo', 'bar') // true

Note that when you check for multiple classes at once, it’s an or function, meaning that the function will return true if el has any of the classes provided.

Clone this wiki locally