ArticleZip > Javascript Css How To Add And Remove Multiple Css Classes To An Element

Javascript Css How To Add And Remove Multiple Css Classes To An Element

Adding and removing multiple CSS classes to an element in JavaScript is a handy skill to have in your coding arsenal. By manipulating CSS classes dynamically, you can enhance the styling and behavior of your website or web application. In this guide, we'll walk through the steps to add and remove multiple CSS classes to an element using JavaScript.

To start off, let's consider a simple HTML file with an element that we want to modify:

Html

<title>Add and Remove Multiple CSS Classes</title>
    


    <div id="element" class="container">Hello, World!</div>

In the above code snippet, we have a `

` element with the id "element" and an initial CSS class "container".

Next, let's move on to the JavaScript part where we will be adding and removing CSS classes to the element dynamically:

Javascript

const element = document.getElementById('element');

// Adding CSS classes
element.classList.add('red', 'bold');

// Removing CSS classes
element.classList.remove('container');

In the JavaScript code above, we first select the element using `getElementById` and store it in the `element` variable. To add CSS classes to the element, we use the `classList.add` method and pass the class names as arguments. Similarly, to remove a CSS class, we utilize the `classList.remove` method and provide the class name to be removed.

By executing the above JavaScript code, the element will now have the classes "red" and "bold" added to it, while the class "container" will be removed.

Additionally, you can also toggle CSS classes on and off using the `classList.toggle()` method:

Javascript

element.classList.toggle('italic');

The `classList.toggle()` method adds the class if it is not present on the element, and removes it if it is already present.

In scenarios where you need to check if a class exists on an element before adding or removing it, you can use the `contains` method:

Javascript

if (element.classList.contains('red')) {
    element.classList.remove('red');
} else {
    element.classList.add('red');
}

By using `classList`, you can easily manage CSS classes on elements in a more structured and efficient manner.

In conclusion, being able to add and remove multiple CSS classes to an element using JavaScript provides you with the flexibility to dynamically update the styling and behavior of your web content. Experiment with these techniques in your projects to create more interactive and visually appealing web experiences.