简体   繁体   中英

Selecting all elements except one and its children/grandchildren

I am looking for a way to select all elements except one element and its descendant which might have children/grandchildren or even more. What I exactly wanna do is something like...

$("*").not(".foo, .foo *").bind("touchmove",function(e){
    e.preventDefault();
});

this would disable all touchmove event except foo class and its children. But unfortunately I don't know how many generations it would have because the code I'm about to write would be used in alot of templates file so they might have no children at all or maybe they have 10 generations family.

is there any way to achive this? other than making new dev/span to wrap everyone else but the one I don't wanna select.(this solution would take really long time for some reason.)

any suggestion or recommendation would be appreciated.

Your code does exactly what you want:

JSFiddle example

Have you tried it? I made a small example with hover to make it visible + I selected only div's and p's to make it easier, but it will work with all the elements as well.

$("div,p").not(".foo, .foo *").hover(function(){
    $(this).css("background", "#70A5C9");
},function(){
    $(this).css("background", "#ffffff");
});

It works because every descendant inherits the classes of his ancestors. In my example you can see that the deepest div will have all the fooX class ( 1 < X < 6).

See another visible example , once I give foo3 a new background color, all the inner foos will have the same background color.

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