Skip to content

toggleClass

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

This function toggles one or more classes from an HTMLElement object. Any class given that the object does not have will be added, while any class that it does have will be removed.

Parameters

el
This is the HTMLElement object from which you would like to toggle one or more classes.
classes
The class or classes you would like to toggle on the HTMLElement object. 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>

The comments in each example show what you can expect the body of the page to be after running the code.

Toggling a class

import { toggleClass } from 'unobtrusive-dom'

toggleClass(document.getElementById('example1'), 'foo')
toggleClass(document.getElementById('example2'), 'foo')
toggleClass(document.getElementById('example3'), 'foo')
toggleClass(document.getElementById('example4'), 'foo')

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

Toggling multiple classes

import { toggleClass } from 'unobtrusive-dom'

toggleClass(document.getElementById('example1'), 'foo', 'bar', 'baz')
toggleClass(document.getElementById('example2'), 'foo', 'bar', 'baz')
toggleClass(document.getElementById('example3'), 'foo', 'bar', 'baz')
toggleClass(document.getElementById('example4'), 'foo', 'bar', 'baz')

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

Clone this wiki locally