简体   繁体   中英

Cannot select all elements except one

I am trying to select all the elements of a page except one, inside a function:

$('#sidebutton').click(function () {

if (!$('.sidemenu').hasClass("current")) {
    prevScrolPos = $(window).scrollTop();
    scrollTo = 0;
} else {
    scrollTo = prevScrolPos;
}

$('.hidelem').toggleClass("hidden");
$('.sidemenu').toggleClass("current"); 
$('html,body').scrollTop(scrollTo);
});

It works when I use a simple class selector (.hidelem), but doesn't when I use something a bit more complicated (for example, $("*:not(.sidemenu)").toggleClass("hidden"); or $("*").not(".sidemenu").toggleClass("hidden"); ); these just lead to a blank window.

Could you tell me what I'm missing here?

JSFiddle: https://jsfiddle.net/et978wjw/5/ (full functionality is missing but I hope you get the idea)

The problem is that you may be skipping .sideMenu with $("body *:not(.sidemenu)") , but you are not skipping its parent DIV. If you hide an ancestor, you hide all its descendants too. You also do not skip any descendants, so the children of .sidemenu are also hidden

So you need to exclude anything that is an ancestor of .sidemenu with :not:(has()) , then exclude the sidemenu itself, then exclude any children of sidemenu:

$("#container :not(:has(.sidemenu)):not(.sidemenu):not('.sidemenu *')").toggleClass("hidden");

JSFiddle: https://jsfiddle.net/TrueBlueAussie/et978wjw/8/

You really should direct the hide/show at something more specific though. Perhaps a wrapper div around everything you want hidden? I added one for the demo.

Now having said all that, your selection process is quite complicated. You would be better off simply adding a class to all the things you want to toggle instead and just toggle those (you already have nodisplay on the divs, so I used that for now).

eg just this:

$(".nodisplay").toggleClass("hidden");

JSFiddle: https://jsfiddle.net/TrueBlueAussie/et978wjw/9/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM