add and remove active class

Add and Remove Active Class

Adding and removing an active class in HTML is a common practice when it comes to styling elements based on user interaction. An active class is used to highlight the currently selected element in a group of elements. Here are some ways to add and remove active classes:

Method 1: Using JavaScript

The most common way to add and remove active classes is using JavaScript. First, we need to select the elements that we want to add or remove the active class from. We can use the querySelectorAll() method to select all the elements with a specific class or tag.

const elements = document.querySelectorAll('.element');

We can then add an event listener to each element that listens for a specific user interaction, such as a click or hover. Once the user interacts with the element, we can remove the active class from all the elements and add it to the selected element.

elements.forEach(element => {
  element.addEventListener('click', () => {
    elements.forEach(element => {
      element.classList.remove('active');
    });
    element.classList.add('active');
  });
});

This code will remove the active class from all the elements and add it only to the clicked element.

Method 2: Using CSS

We can also add and remove active classes using CSS. We can use the :active pseudo-class to target the currently selected element. We can then use the classList property in JavaScript to add or remove the active class based on user interaction.

 <div class="element"><p>Element 1</p></div>
 <div class="element"><p>Element 2</p></div>
.element:active {
  background-color: blue;
}
const elements = document.querySelectorAll('.element');

elements.forEach(element => {
  element.addEventListener('click', () => {
    elements.forEach(element => {
      element.classList.remove('active');
    });
    element.classList.add('active');
  });
});

This code will change the background color of the currently selected element to blue.

Method 3: Using jQuery

If you're using jQuery, adding and removing active classes is even easier. We can use the toggleClass() method to add or remove the active class based on user interaction.

<div class="element"><p>Element 1</p></div>
<div class="element"><p>Element 2</p></div>
$('.element').click(function() {
  $('.element').removeClass('active');
  $(this).addClass('active');
});

This code will remove the active class from all the elements and add it only to the clicked element.

In conclusion, adding and removing active classes is a simple and effective way to highlight the currently selected element in a group of elements. Whether you're using JavaScript, CSS, or jQuery, there are multiple ways to achieve this effect.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe