What is a more sophisticated approach to adding css to "every element except this one"?

I am currently using html/jQuery to create tabbed navigation on my website. I have managed to make the selected tab appear active by adding a CSS class "active" and changing the previous tabs to have an "inactive" class. In order to achieve this, I have included the following code in my click event:

$("ul.tabs li").removeClass("active"); //Remove any "active" class
$("ul.tabs li").addClass("inactive");  //Set all to "inactive"
$(this).removeClass("inactive");  //remove "inactive" from the item that was clicked
$(this).addClass("active"); //Add "active" class to the item that was clicked.

Although this method works, I am interested in hearing if there is a more efficient or cleaner approach to accomplishing the same result?

Answer №1

$(document).ready(function(){
    $("ul.tabs li").on("click", function(){
        $(".active").toggleClass("active inactive");
        $(this).toggleClass("inactive active");
    });
});

Check out the live demo here: http://jsfiddle.net/1dJWz/

Answer №2

What is the reason for not setting the inactive style as the default style? In this case, you could simply use the following code:

$("ul.tabs li").removeClass("active");
$(this).addClass("active");

Answer №3

$(this).removeClass("inactive").addClass("active").siblings().removeClass("active").addClass("inactive");

Keep in mind that it is advised to avoid using $('ul.tabs li') within an element's click event. This way, when dealing with multiple .tabs, only the one related to the clicked element will be affected.

Alternatively, it is recommended to implement CSS rules to eliminate the necessity of the inactive class, as shown below:

ul.tabs li {…} /* Inactive state */
ul.tabs li.active {…} /* Active state */

Answer №4

Have you thought about targeting elements with the specified class and removing it that way? You can condense the process into just two lines:

$('.active').removeClass('active').addClass('inactive');
$(this).addClass('active').removeClass('inactive');

Answer №5

This method ensures the selectors are only evaluated once.

$("ul.tabs li").removeClass("active").addClass("inactive");
$(this).removeClass("inactive").addClass("active");

I concur with the previous suggestions, it would be more efficient to eliminate the inactive class altogether. Set the default tab styling to "inactive" and toggle the active class as needed. Place the CSS for the "active" class after the base CSS for the tabs so that it takes precedence over the default state. With this approach, your code simplifies to:

$("ul.tabs li.active").removeClass("active");
$(this).addClass("active");

Answer №6

Opting for :not() proves to be significantly speedier than using .not(). In place of repeatedly adding and removing classes, consider employing jQuery's toggleClass() method. Here is how your code snippet should look:

    $("ul.tabs li:not(" + $(this) + ")").toggleClass("active", "inactive");
$(this).addClass('active');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Cause the browser icon to flash in the taskbar when a notification is received

After creating a monitor page for our product services, I wanted users to easily check the status of different services on that page. Now I am looking for a way to make the browser icon on the taskbar blink whenever there is an alert and the browser is mi ...

The generation of noisy URLs with hidden inputs is caused by the checkboxes in Thymeleaf Spring forms

Thymeleaf Spring automatically generates hidden inputs for checkboxes in forms, as explained in the documentation at When submitting the form using a GET method, the resulting URL can be quite lengthy and noisy: /search?q=stuff&_filters=on&filter ...

Unit tests in Vue 3 do not utilize configureWebpack in vue.config.js

Within my Vue configuration, the following code snippet can be found: configureWebpack: { resolve: { alias: { react: path.resolve(__dirname, 'composition/react'), hooks: path.resolve(__dirname, 'composition'), }, ...

What is the best way to add color to the "ngx-star-rating" component?

I've been experimenting with the ngx-star-rating plugin, and I've tested different approaches like fill and color, but nothing seems to be working! Can anyone provide suggestions on how to change the star rating color from yellow to a different c ...

How to run JavaScript code in Robot Framework using Selenium2Library

I am currently conducting automated testing on a web application based on extjs using robotframework and selenium2library. However, I'm facing difficulty in locating certain elements within a table component. I have come across the Execute JavaScript ...

Adding padding-top to the h1 element within a vertically aligned div

I have a div with a set height and the content inside adjusts vertically according to the height. To align it vertically, I added the property display-table; to the parent div and display: table-cell; vertical-align: middle; to the child div. The alignment ...

"Challenges encountered when using map function to dynamically fill select dropdowns in React with Material UI

I am currently working on populating Material's UI with a list of countries using the following code: import React from "react"; import FormControl from "@material-ui/core/FormControl"; import InputLabel from "@material-ui/core/InputLabel"; import Se ...

Issue with Vue Router not rendering components after dynamically importing them

I am facing an issue with vue-router while trying to register components dynamically. When I use hardcoded code, the router functions properly. However, when I load my routes dynamically, it fails to render the component. The component file is being impor ...

How to style a form using Django and jQuery

Currently, I am experimenting with using jQuery to style a Django form. This is a new endeavor for me with jQuery. My goal is to divide the form into smaller subgroups that can be extended upon click or based on selections made within the form. (I wonder i ...

Combining numerous done() callbacks to a single deferred promise

Basically, I am looking to implement a single general callback that triggers every time an ajax call is successful, with additional specific callbacks based on where the method is called. It appears to be functioning properly. My query pertains to whether ...

How to enhance MVC form validation across multiple tabs by automatically navigating to the tab containing validation errors?

My web page includes a tabstrip that contains multiple tabs, each with several text fields for user input. The tabstrip is enclosed in a form and located just below a submit button. I have implemented model attribute annotations for validation on the text ...

What could be causing the distance between the image and the navigation bar?

Hey there, I'm struggling with a pesky little gap that's sneaking in between an image and my navigation bar. I've exhausted all my usual tricks like setting inline-blocks on the ul and li levels, and trying to align everything left with text ...

Exploring the methods for retrieving and setting values with app.set() and app.get()

As I am granting access to pages using tools like connect-roles and loopback, a question arises regarding how I can retrieve the customer's role, read the session, and manage routes through connect-roles. For instance, when a client logs in, I retrie ...

Plot the highest-ranked outcomes based on a search using Google Maps

I'm currently facing a challenge in integrating different components. I have successfully created a php page to display results from a mysql database and can also retrieve addresses for mapping with Google. However, I am struggling to combine both fun ...

VueJS: Even when disabled, clicking a button can still navigate to a different

Is there a way to prevent the button from being clickable when the current page is the first page? Although the button disables as expected, I'm still encountering an issue where the route changes when it's clicked. Code Snippet (Javascript) ...

How can I dynamically toggle the visibility of a dynamically generated <div> in Angular 8 based on its id?

When working with an Angular 8 component, I am dynamically generating a number of <table> elements from an input array. Each <table> includes a <tr> at the end which contains a hidden <div> along with a button. The goal is to togg ...

Issue with React component not reflecting updated state following Axios call

I have a series of chained axios calls to different APIs. When I log the state inside the function, I see that it is being updated correctly. However, when I log the state in the render() method, I do not see the updated state. The function is triggered a ...

Is the value being sent correctly from my jQuery to the controller?

Currently, I am in the process of utilizing jQuery to perform a delete operation on a table, $('table#chkbox td a.delete').click(function() { if (confirm("Are you certain you wish to delete this row?")) { var id = ...

Prioritizing tasks, always giving a call once they are completed

I am trying to populate an HTML snippet with data from Firebase. Here is the JavaScript code I wrote to achieve this: members.forEach(el => { console.log(el) table_number++; console.log("forEachMember" + table ...

IE and Chrome are experiencing issues where the radio buttons are disappearing

Here is the style sheet code: select,input ,td a {border:1px solid green; width:25%;height:25px;font-size:20px;margin- left:.1em;} input.myradio {border:none;width:0%;height:0%;font-size:0%;} And here is the corresponding HTML code: <td><inpu ...