DEV Community

Cover image for How to add and remove class in html elements using JS.
Mysterio
Mysterio

Posted on • Updated on

How to add and remove class in html elements using JS.

Hello Guys today i am going to show you how you can add or remove class of html elements using javascript.It will help you to add class and its related styling dynamically using button event handlers.
Lets get started...

HTML -

 <div id="box">
      <h1 id="heading">
        Hello Dom Manipulation
      </h1>
      <div>
        <button type="button" class="btn btn-outline-primary"             
         onclick="Animation1('Animation1')">Animation1</button>
      <div>
        <button class="btn btn-outline-danger my-5" 
                onclick="refresh()">Refresh</button>
      </div>
</div>

Enter fullscreen mode Exit fullscreen mode
  • We have created two button elements inside a div with id="box".
  • The first button is used to add the class to the H1 element with id="heading" and the second button is used to remove the class from the H1 element with id ="heading".
  • The first button have the onclick event handler and inside it we have called a function named "Animation" inside the parameter we have passed the class name which we want to add to the H1 element with id="heading" and same with the second button whose onclick event handler has a function call named "refresh" and inside it we have passed the class name which we want to remove as the parameter of the function.

CSS -

#box{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: black;
    flex-direction: column;
}
#heading{
    color: crimson;
    font-size: 5rem;
    margin: 0 0 8rem 0;
    border-radius: 10px;
}

.Animation1{
    animation-name: animation1;
    animation-fill-mode: forwards;
    animation-duration: 2s;
    animation-iteration-count: 1;
    transition: all 2s ease;
}

@keyframes animation1 {
    0%{
        color: darkcyan;
    }
    20%{
        color: cyan;
    }
    40%{
        color: purple;
    }
    60%{
        color: rebeccapurple;
    }
    80%{
        color: salmon;
    }
    100%{
        color: tomato;
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Here we have defined the styles for all the elements using their id names .
  • We have defined the styles for the "Animation" class and also attached an animation with it.So when the "Animation" class is added to the H1 element , then the animation will be executed.

Javascript -

/* first getting the element using its id name and then through 
dom manipulation (elementName.classList.add(className)) we have
 added the class to the H1 tag */

let box = document.getElementById("heading");
const Animation1 = (animate) => {
box.classList.add(animate);
}

const refresh = () => {
/*.contains check that the class is already present or 
not , if it is present , then the class will be 
removed , otherwise we will get an alert message*/

if(box.classList.contains("Animation1")){
box.classList.remove("Animation1");
alert("All the animations are refreshed");
 }
else{
alert("No animation is executed yet")
 }
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT -

1. The starting point of the program

Image description

2. The Text color is changed because we have added the "Animation1" class to the H1 tag using Animation1 button and the animation gets executer.

Image description

3. The alert messages appears because we had removed the "Animation1" class using the refresh button .

Image description

NOTE - I HAVE USED BOOTSTRAP IN THIS TUTORIAL SO INSTALL IT USING NPM OR ADD IT THROUGH CDN.

^^You can help me by some donation at the link below Thank you👇👇 ^^

☕ --> https://www.buymeacoffee.com/waaduheck <--

THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE ANY SUGGESTION , PLEASE MENTION IT IN THE COMMENT SECTION.

Also check these posts as well

  1. https://dev.to/shubhamtiwari909/animation-with-react-spring-3k22

  2. https://dev.to/shubhamtiwari909/text-to-speech-in-reactjs-52ml

  3. https://dev.to/shubhamtiwari909/best-vs-code-extensions-for-web-development-2lk3

Discussion (2)

Collapse
lukeshiru profile image
Luke Shiru

If you're toggling between having and not having a classname, you could just use .toggle instead of .add and .remove. Also ideally you should move the event handlers to JS, so the HTML would look more like this:

<div id="box">
    <h1 id="heading">Hello Dom Manipulation</h1>
    <div>
        <button type="button" class="btn btn-outline-primary toggle-animation">
            Toggle animation
        </button>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

And the JS more like this:

const toggleClass = className => element => () =>
    element.classList.toggle(className);

const toggleAnimation1 = toggleClass("Animation1");

document
    .querySelector(".toggle-animation")
    .addEventListener(
        "click",
        toggleAnimation1(document.querySelector("#heading")),
    );
Enter fullscreen mode Exit fullscreen mode

One last thing: Remember that alert is a blocking function, meaning that while the alert is open, the app is frozen on the back. Ideally you should try to use other approach to communicate with the user that allows you to keep the app running in the background (like the dialog element).

Cheers!

Collapse
shubhamtiwari909 profile image
Mysterio Author

Thanks for the correction sir 🤠🤠