-
Notifications
You must be signed in to change notification settings - Fork 0
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.
el- This is the
HTMLElementobject from which you would like to toggle one or more classes. classes- The class or classes you would like to toggle on the
HTMLElementobject. 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.
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.
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>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>