how to change class by is in js by toggle
How to Change Class by "is" in JS by Toggle
If you want to change the class of an element by checking if it has a certain class, you can use the toggle
method in JavaScript. Here's how:
Step 1: Get the Element
First, you need to get the element you want to change the class of. You can use a variety of methods to do this, but one common way is to use the getElementById
method:
const myElement = document.getElementById("my-element");
Step 2: Use Toggle to Change the Class
Once you have the element, you can use the classList.toggle
method to add or remove a class based on whether or not the element already has that class:
myElement.classList.toggle("my-class");
In this example, if myElement
already has the class my-class
, it will be removed. If it doesn't have the class, it will be added.
Step 3: Add "is" for BEM Naming Convention
If you're using the BEM naming convention, you'll want to add a modifier to your class that indicates its state. The convention for this is to add "-is" followed by the state name. For example, if you have a button that is disabled, you would add the class button-is-disabled
.
To add a "is" modifier to your class using the toggle
method, simply add it as part of the class name:
myElement.classList.toggle("my-class-is-active");
In this example, if myElement
already has the class my-class-is-active
, it will be removed. If it doesn't have the class, it will be added.
Alternative Method: Use Contains to Check for Class
Another way to check if an element has a certain class is to use the contains
method. This method returns a boolean value indicating whether or not the element has the specified class:
if (myElement.classList.contains("my-class")) {
myElement.classList.remove("my-class");
} else {
myElement.classList.add("my-class");
}
In this example, if myElement
already has the class my-class
, it will be removed. If it doesn't have the class, it will be added.
Conclusion
There are multiple ways to change the class of an element based on whether or not it already has a certain class. The toggle
method is a simple and concise way to do this, but you can also use the contains
method to check for the presence of a class before adding or removing it.