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

Tips for resolving undefined error handling in node.js

const fileSystem = require('fs'); const fileName = './prices.json'; const file = require(fileName); const price = require('./prices.json'); const fileName = './prices.json'; if(tmd = message.match(/^!change max ...

Running a child process within a React application

I'm currently in search of the best module to use for running a child process from within a React application. Here's what I need: I want a button that, when clicked, will execute "npm test" for my application and generate a report that can be r ...

Avoiding multiple ajax requests due to multiple clicks

I have a blog on WordPress that has a jQuery code allowing users to click a bookmark link to save the post as a bookmark. Each post displays a total bookmark counter in this format: "Bookmarked (5)". The issue is that when a user clicks multiple times on t ...

Is it possible to identify users using an iPhone while they are utilizing "Private Browsing" mode?

Looking for a solution to detect private browsing mode in my jquerymobile App. I need localStorage and sessionstorage to work properly, but prompting users to enable cookies when private browsing is enabled doesn't solve the issue. Is there a way to t ...

Update the configurable product process for the custom attribute 'delivery_time' in Magento 1.9.2

I am currently using Magento 1.9.2.4 (1.9.2.3 in my Testpage) and I have a few configurable products with multiple options. Each product (child of the configurable one) has a different delivery time. To achieve this, I created an attribute called "delivery ...

Activating Ionic6 Stack Modal through JavaScript or TypeScript

Is it possible to trigger the modal using script code instead of a button? I have searched through various examples in the tutorial, but all of them rely on the modal trigger mechanism. <ion-button id="open-modal" expand="block">O ...

Receiving an item in place of a true/false indicator

I wrote an asynchronous function that validates the permission status on a device. Here is the function: checkPermission = async () => { const allowed = await requestNotifications(['alert', 'sound']).then((res) => { if ...

What is the process for retrieving the value of a text box using V-Model?

Link to the code snippet <td><input class="input" v-model="user.name" /></td> After accessing the provided link, I noticed a unique input textbox. Is there a way to extract specific text values like a,b,c from this te ...

Ways of extracting specific information from a JSON file with the help of jQuery

I am currently attempting to parse a JSON file that is stored locally on my system using jQuery. I am specifically interested in retrieving certain data from the file, which is structured like this: {"statements":[{"subject":{"uriString":"A","localNameIdx ...

Extremely sluggish pagination in JQGrid following the implementation of a filter through the filter toolbar

I've encountered a problem while using jqGrid with LOAD ONCE and client-side paging. The addition of a filter toolbar has significantly slowed down the paging process after applying any kind of filter. $(gridElement).jqGrid({ postData: post, ...

Ways to implement the don't repeat yourself (DRY) principle in React JS with condition-based logic

https://i.stack.imgur.com/xkrEV.gif Here is a sample way to use the component: import React from "react"; import MyAvatars from "../../components/MyAvatar/MyAvatars"; const About = () => { return ( <MyAvatars ...

The h3 element is not responding to the adjacent sibling selector

Below is my HTML DOM structure. I am trying to remove the margin and padding for all h3 elements that are immediate siblings of a div with the id "successor". I attempted to achieve this using the adjacent sibling selector "+", but unfortunately, I'm ...

Struggling to locate the Twitter direct message input box with Xpath in Selenium

I have been struggling to locate the textbox element using the find_element_by_xpath() method. Unfortunately, every time I try it, I receive an error stating that the element cannot be found. Here is the specific line of code in question: Despite attempti ...

Display the page for 10 seconds continuously in a loop

I am currently developing a Node JS guessing game where data is collected on the back-end and sent to the front-end to start the game. The data consists of 10 levels, allowing the game to operate on a single page. Each level lasts for 10 seconds. Once the ...

Unusual behavior observed in AngularJs local variables

This code snippet is from the controller: cat1=[]; $.getJSON('categories/1/', function(data) { cat1 = data; //this returns a JSON object }); //cat2..4 are also JSONs $scope.pictures=[cat1,cat2,cat3,cat4,cat5]; The issue here seems to be th ...

Resolving the bothersome complications of self-looping steps in jQuery animate delay

My timeline definition includes selectors and a sequence of delays and animations to apply to an object. I have also provided the option to loop through the steps for a specific object. Here is the function that I use to queue the animations: function an ...

Creating dynamic button names and detecting the pressed button in PHP

Right now, I am experimenting with PHP to create a unique project. This experiment is just a small part of a larger file that I am working on. Essentially, the aim is for the program to generate a series of submit buttons within a form, each assigned a dis ...

Inquiries regarding node.js

While delving into research on node.js and Mongodb, I encountered a few areas that require clarification. My aim is to query Mongodb from the web using JavaScript because of my familiarity with the language. Additionally, it aligns well with Mongodb' ...

AJAX Promises Ignoring Completion Status

After extensively researching on Stack Overflow and other sources, I am still unable to resolve this issue. My goal is to retrieve a user's credits before they can make a purchase. Initially, everything was functioning correctly until recently. Below ...

A guide on rotating loaders and inserting custom text within loaders using CSS

Seeking assistance to modify my code for creating a unique loader design. The inner loader needs to remain static with only top and bottom segments, while the middle loader rotates anti-clockwise and the outer loader rotates clockwise. Additionally, the ...