JavaScript Toggle Between Two Classes

JavaScript Toggle Between Two Classes

In today’s article, we look at toggle to a CSS class between two classes in easy step-by-steps.

There are server ways to do that like classList.toggle(), classList.contains(), className, jQuery and many more methods and way.

To keep it more simple and easy we will use JavaScript function method(),

When an HTML element toggle event occurs in JavaScript, you can perform various actions such as changing the text or background color, adding a border, displaying different text, and more.

Adding two paragraph to a button click.

Step 1 :Create a HTML button.

Start by creating a simple HTML button with some text and also add an ID to the button so we can select in the JS file using querySelector.

Syntax:

<button id=btn>Click Me</button>

As you can see in the above code, there is a button with a simple text named “Click Me” and ID whose name is “btn”.

Step 2: Select “ID” in JS file.

Once you are done creating the button and adding the ID, now select that ID in your JavaScript file

You can use the query selector to store your ID (“myid”), for example:

let btnvalue = document.querySelector(#btn);

This is how you can get your HTML button in JavaScript using ld and document.querySelector

Step 3: Create a Function.

Now in this third step we are going to create a simple function like when my button is clicked I want two different paragraphs, here is the example.

function myfunction() {
console.log(This First Para);
console.log(This Second Para);
}

In the above example I have a function called “myfunction” and two different console logs, the first is “this first para” and the second is “this second para”

So when my button is clicked these two paragraphs will appear in the console.

Step 4: Apply addEventListener.

We need to put addEventListener on the button in the last step before we can see the console. Below is an example

Syntax:

btnvalue.addEventListener(click, myfunction);

On the above code I have my button’s variable called “btnvalue” and have an EventListener attached to it, then after calling the entire function on click method which is “myfunction”.

Step 5: Save and output.

Once you have followed all the steps now save the file and see the output using console log, here is my final output

Output:

As you can see, I toggle between my two classes using a function. You can customize this method to print, display, change styles, or modify the HTML as per your needs.

I hope this post helps you to know How to Toggle Class Between two Classes in JavaScript.