Hide all elements in jQuery that do not have a class assigned

I've implemented a straightforward jQuery script that toggles the "active" class on an li element when it is clicked:

$('li').click(function() {
    $(this).toggleClass('active');
});

My goal is to hide all other li elements in the list when one is made active by setting their display property to none. Then, when the same active li is clicked again, I want to remove the active class and show all other li elements once more. However, achieving this has been challenging for me.

Initially, I attempted using an if statement inside the click function to check for the presence of the "active" class. If found, I set all li elements to be hidden; if not, I tried resetting their CSS properties to make them visible again. Unfortunately, this approach did not yield the desired results.

In an edit, I mentioned that tilz0R's solution was close to what I needed. With some slight modifications, I managed to adapt it to suit my requirements:

$('li').click(function() {
    $(this).toggleClass('active').siblings().toggleClass('hidden');
});

The 'hidden' class simply contains a display property of none, allowing all li elements, except the one clicked, to be hidden. Clicking the active li a second time will cause all li elements to be displayed once more.

Answer №1

In order to locate the siblings of the existing li element, a specific method must be used.

$('li').click(function() {
    $(this).toggleClass('active').siblings().hide();
});

Answer №2

To implement this functionality, you can use the jQuery methods addClass, removeClass, and show() / hide()

$('li').click(function() {
  if ($(this).hasClass('active')) {
    $('li').show();
    $(this).removeClass('active');
  } else {
    $('li').hide();
    $(this).addClass('active').show();
  }
});
li {
  cursor: pointer;
}

.active {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
</ol>

Answer №3

By clicking on any <li> element, all other <li> elements will be hidden except the one that is clicked. Clicking again will reveal all <li> elements and remove the active class.

HTML:

<ul>
  <li>apple</li>
  <li>banana</li>
  <li>cherry</li>
  <li>date</li>
</ul>

JavaScript:

jQuery('ul li').click(function() {
      if(jQuery(this).hasClass('active')) {
        jQuery(this).removeClass('active');
        jQuery('ul li:not(".active")').show();
      } else {
        jQuery('ul li').removeClass('active');
        jQuery(this).addClass('active');
        jQuery('ul li:not(".active")').hide();
      }
    });

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

Executing an Amplifyjs GET request containing a request body

Is it possible to utilize GET requests with a message body using AmplifyJS? Specifically, I am curious about the process of achieving this functionality with AmplifyJS. While synthetic tests function properly (using Fiddler as my test client), I have enc ...

Preventing simultaneous ajax requests

Similar Question: How to stop a jquery.load() request? So I'm dealing with an autocomplete field that's sending an ajax request every time a key is pressed, causing significant slowdown. If you check out this link and log in with the details ...

Attempting to retrieve AJAX response in JavaScript by utilizing an OOP object

Here is the code snippet I am working with: function CreateDiv(D) { D.body = function () { var d = $.ajax({ type: "GET", url: "Default.aspx", data: 'Ext ...

choosing a section within a table cell

This seems like a simple task, but I'm encountering some difficulties $("#info-table tbody tr").each(function(){ $(this).find(".label").addClass("black"); }); .black{ font-weight:bold; } <script src="https://ajax.googleapis.com/ajax/libs/j ...

Error: The `Field` component encountered a failed prop type validation due to an invalid prop `component` after upgrading to MUI version

Encountered an error when migrating to Material ui v4 Failed prop type: Invalid prop component supplied to Field. in Field (created by TextField) This error points to the redux form field component export const TextField = props => ( <Field ...

Employing conditional statements in conjunction with styled components

Is there a way to style my PaymentBtn with the main styled Button but only apply the hover effect when the isLoading prop is activated, without changing anything else? I want the styling to remain the same except for the hover effect. Basic button export ...

Adjust the text input width appropriately for the cloze exercise

My JavaScript-generated fill-in-the-blank text is causing me trouble when it comes to adjusting the size of the input boxes. Unlike others, I know exactly what the user will or should be entering. If there is a blank space like this _______________, I wa ...

When attempting to navigate to a different page in Next.js, the Cypress visit functionality may not function as

In my upcoming application, there are two main pages: Login and Cars. On the Cars page, users can click on a specific car to view more details about it. The URL format is as follows: /cars for the general cars page and /cars/car-id for the individual car p ...

The layout of the divs becomes distorted when the window is resized

When adjusting the window size, all elements in the center become cramped and unresponsive. Even the navigation items in the header do not resize properly. Here is my Triangle.js file: import React from 'react' import { motion } from 'fram ...

How can I access the variable that evaluated as true in an if statement?

I'm facing a bit of a challenge with testing 2 variables for the same value. Is there a way to achieve this? var x = 'abc'; var y = 'def'; if (x=='abc' || y=='abc'){ z = 'result&a ...

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...

The changes made in Express are not reflecting in the MongoDB database as expected

I'm having trouble with my update function. It's not a database issue because delete works fine. Here is the code for my Update route: Can someone please assist me? I've been using console.log to display values in the console, and they all ...

Updating the value of a Redux-Form Checkbox Field using programming methods

I have created a registration form where users can accept or decline the terms of services. When a user accepts the terms, they click a button to check the checkbox. If they decline, the button will uncheck the checkbox. https://i.sstatic.net/mfkcY.png ht ...

The focus is on the last row that was selected

I've noticed that when I check and select a row in ui-grid, only the last selected row is focused with a background color. Should all rows be automatically painted by default? Thank you. ...

Save this code snippet to your clipboard using vanilla JavaScript (no jQuery needed)

I am working on an Angular 9 application where I want to implement the functionality of copying the URL to clipboard when clicked. Currently, I have the following code: The issue I am facing is that it only copies the URL on the second attempt and then st ...

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...

Retain selected choices even after refreshing the page using PHP

Working on a smaller project using PHP, I encountered a problem that has left me feeling lost. Let me break it down into two parts. Part 1: In my project, I have an index.php file and a getitem.php file. The index file contains a form with multiple select ...

Webpack fails to handle CSS background images

I'm having trouble with my Webpack configuration as it's not processing CSS images set in the background property: background: url('./hero.jpg') no-repeat right; This is resulting in an error message that reads: ERROR in ./src/app/comp ...

Updating Sencha list itemTpl on the fly

Is there a way to dynamically change the itemTpl in a Sencha list to adjust the visibility of a column based on certain conditions? Your assistance would be greatly appreciated. ...

Can a JavaScript file be imported exclusively for a Vue component?

When attempting to utilize the table component in the vue-ant framework, I am facing an issue. I am only looking to import the table style, but when I try to import the table style using import 'ant-design-vue/lib/table/style/css', it affects all ...