Javascript Remove Class From All Elements Except Current One

Last Updated: 2023-07-31 05:50:15

Javascript Remove Class From All Elements Except One

Previously we have discussed how to add a class to an HTML element in javascript. Now in this post, we will discuss how to remove a class from all HTML elements except the current one. If you understand our previous post, this post will be easy for you. Will will discuss real-life examples and source code. So that you can apply the techniques in your projects. So will cover the following things:

  1. How to remove a class from an HTML element in javascript
  2. How to remove the active class from the menu in javascript
  3. How to remove a class from all targeted HTML elements in javascript
  4. How to remove a class from all elements except One

 

How to remove a class from an HTML element in javascript

JavaScript has its own default function to remove a class from an HTML element. We can use that default function to remove our targeted class from the targeted HTML element. Suppose, you have a button that has a class named btn-red now you want to remove this class from your button.

Code Example

 

< button id="myButton" class="btn-red">Click me< /button>
// Get the button element by its ID
const myButton = document.getElementById('myButton');

// Remove the class "btn-red" from the button
myButton.classList.remove('btn-red');

You can remove a class from an HTML element using JavaScript by using the classList property of the element. Specifically, you can use the remove() method of the classList property to remove a class from the element. In your case, to remove the class "btn-red" from a button element.

 

 

How to remove a class from all targeted HTML elements in javascript

Sometimes we need to remove a class from all of our targeted HTML elements. In this case, we can use javascript to do this. Suppose from all of the DIV tags you want to remove the bg-dark class when the user clicks on a button. In this case, you can follow this implementation.

Code Example

< !-- Example: some divs with class "bg-dark" -->
< div class="bg-dark">Div 1< /div>
< div class="bg-dark">Div 2< /div>
< div class="bg-dark">Div 3< /div>
< div class="bg-dark">Div 4< /div>

< !-- Button to trigger class removal -->
< button id="removeClassButton">Remove bg-dark Class< /button>

// Get the button element by its ID
const removeClassButton = document.getElementById('removeClassButton');

// Add a click event listener to the button
removeClassButton.addEventListener('click', () => {
  // Get all elements with the class "bg-dark" and store them in a variable called "bgDarkElements"
  const bgDarkElements = document.querySelectorAll('.bg-dark');

  // Loop through each element and remove the "bg-dark" class from it
  bgDarkElements.forEach(element => {
    element.classList.remove('bg-dark');
  });
});

In this implementation:

  1. We first select the button element using getElementById() and store it in the removeClassButton variable.
  2. Then, we add a click event listener to the button using addEventListener(). When the button is clicked, the function inside the event listener will be executed.
  3. Inside the click event listener, we use document.querySelectorAll('.bg-dark') to select all elements with the class "bg-dark." The querySelectorAll method returns a NodeList of all elements that match the specified selector.
  4. We store this NodeList in a variable called bgDarkElements.
  5. Next, we use bgDarkElements.forEach(element => { ... }) to loop through each element in the bgDarkElements NodeList.
  6. For each element, we call element.classList.remove('bg-dark') to remove the "bg-dark" class from it.
  7. So, when the user clicks the button, the JavaScript code will remove the "bg-dark" class from all < div> tags that have the class "bg-dark," effectively removing the background color style specified by that class.

 

 

 

How to remove the active class from the menu in javascript

To make our menu item active we add an active class to the menu item. So, to make your menu item deactivate you need to remove that active class from your menu item. Now in this section, we will discuss how to remove the active class from the menu item in javascript. You already know how to remove a class from an HTML element so if you try your own I think you will be able to do this easily. Suppose you have a menu with 5 items now you want to remove the active class from all items except the current one. In this class you need to follow the following implementation:

Code Example

< ul id="menu">
    < li class="menu-item active">Item 1< /li>
    < li class="menu-item">Item 2< /li>
    < li class="menu-item">Item 3< /li>
    < li class="menu-item">Item 4< /li>
    < li class="menu-item">Item 5< /li>
< /ul>
// Get all the menu items and store them in a variable called "menuItems"
const menuItems = document.querySelectorAll('.menu-item');

// Loop through each menu item and add a click event listener to it
menuItems.forEach(item => {
  item.addEventListener('click', () => {
    // Inside the click event, we will perform the following actions:

    // Step 3: Remove the active class from all menu items
    menuItems.forEach(menuItem => {
      menuItem.classList.remove('active');
    });

    // Step 4: Add the active class to the clicked menu item
    item.classList.add('active');
  });
});

Code Explanation

 

  1. document.querySelectorAll('.menu-item'): This line of code selects all elements with the class "menu-item" from the HTML document. The querySelectorAll method returns a NodeList containing all the elements that match the given CSS selector (in this case, the class name "menu-item").
  2. const menuItems = ...: We store the NodeList in a constant variable called "menuItems." This variable will now hold a collection of all the menu items in the document.
  3. menuItems.forEach(item => { ... }): We use the forEach method to loop through each menu item in the menuItems collection.
  4. item.addEventListener('click', () => { ... }): For each menu item, we add a click event listener. This means that when a menu item is clicked, the code inside the event listener will be executed.
  5. menuItems.forEach(menuItem => { menuItem.classList.remove('active'); });: Inside the click event listener, we have another forEach loop. This loop goes through all the menu items again (menuItems), and for each menu item, it removes the class "active" from it. This step ensures that we reset the active state for all menu items before adding it to the clicked one.
  6. item.classList.add('active');: After removing the "active" class from all menu items, we add the "active" class to the clicked menu item (item). This makes the clicked menu item visually distinct to indicate that it is the currently selected item.

So, when a user clicks on a menu item, the JavaScript code will remove the "active" class from all menu items and then add the "active" class only to the clicked menu item. This approach allows us to toggle the active state among menu items as users interact with them.

 

 

How to remove a class from all elements except one

You already know how to remove a class from all elements. Now in this section, we will learn how to remove a class from all elements except the targeted one. For example, suppose you have 5 divs now you want to remove bg-blue class from all the divs except the special one having the class name special-div. You want to do this when a user clicks on a button.

Code Example

< div class="div-box bg-blue">Div 1< /div>
< div class="div-box bg-blue">Div 2< /div>
< div class="div-box bg-blue special-div">Special Div< /div>
< div class="div-box bg-blue">Div 3< /div>
< div class="div-box bg-blue">Div 4< /div>

< button id="remove-bg-button">Remove bg-blue class< /button>

JavaScript removes the class from all except the special one

 


document.getElementById('remove-bg-button').addEventListener('click', function() {
const divs = document.querySelectorAll('.div-box');
	divs.forEach(function(div) {
		if (!div.classList.contains('special-div')) {
			div.classList.remove('bg-blue');
		}
	});
});

In this example, when the button with the ID remove-bg-button is clicked, it triggers the JavaScript function. The function selects all the div elements with the class div-box and then iterates through them using forEach. For each div, it checks if it doesn't have the class special-div, and if so, it removes the class bg-blue from that div.

 

 

 

JQueryremoves the class from all except the special one

 

< script src="https://code.jquery.com/jquery-3.6.0.min.js">< /script>
< script>
  $(document).ready(function() {
    $('#remove-bg-button').on('click', function() {
      $('.div-box:not(.special-div)').removeClass('bg-blue');
    });
  });
< /script>

This code uses jQuery to select the div elements with class div-box that do not have the class special-div, and then it removes the bg-blue class from them when the button is clicked.

 

In conclusion, removing a class from HTML elements is straightforward in JavaScript. This versatile technique that allows developers to dynamically modify the appearance and behavior of elements on a webpage. By manipulating classes, developers can apply or remove specific styles, toggle elements' visibility, or enable/disable certain functionalities based on user interactions or other events.

The process involves selecting the desired HTML elements using various methods such as querySelector or getElementById, and then using the classList property to add or remove classes.

 

Still you face problems, feel free to contact with me, I will try my best to help you.