ArticleZip > How To Add And Remove Classes In Javascript Without Jquery

How To Add And Remove Classes In Javascript Without Jquery

When working with JavaScript, manipulating classes is a common task for web developers. While jQuery has been a popular choice for handling this, with native JavaScript, you can achieve the same functionality without the added weight of a library like jQuery. In this article, we'll explore how to add and remove classes in JavaScript without using jQuery.

### Adding a Class

To add a class to an element using vanilla JavaScript, you first need to select the element you want to modify. You can do this using the `querySelector` method, specifying the CSS selector for the element. Once you have the element, you can manipulate its `classList` property to add a class.

Here's a simple example of adding a class named "newClass" to an element with the id "myElement":

Javascript

const element = document.querySelector('#myElement');
element.classList.add('newClass');

In the code snippet above, we first obtained a reference to the element with the id "myElement" and then added the class "newClass" to it using the `classList.add` method.

### Removing a Class

Removing a class is just as straightforward as adding one. To remove a class from an element, you can use the `classList.remove` method. Continuing from the previous example, let's remove the class "newClass" from our element:

Javascript

const element = document.querySelector('#myElement');
element.classList.remove('newClass');

By calling `classList.remove('newClass')`, we removed the class "newClass" from the element.

### Toggling a Class

Sometimes you might want to toggle a class on and off based on certain conditions. For that, JavaScript provides the `classList.toggle` method. This method adds a class if it's not present on the element, and removes it if it is already present.

Here's an example of toggling a class named "active" on and off when a button is clicked:

Javascript

const button = document.querySelector('#toggleButton');
const element = document.querySelector('#myElement');

button.addEventListener('click', () => {
  element.classList.toggle('active');
});

In this snippet, we added a click event listener to a button with the id "toggleButton", and when clicked, it toggles the class "active" on our element with the id "myElement".

### Conclusion

In this article, we've covered how to add, remove, and toggle classes in JavaScript without the need for jQuery. By leveraging JavaScript's native methods like `classList.add`, `classList.remove`, and `classList.toggle`, you can easily manipulate classes on HTML elements in your projects. Remember, understanding these fundamental concepts will empower you to create dynamic and interactive web experiences without relying on external libraries. Happy coding!

×