JQuery selector not this kid

Is there a way to attach the click event to multiple elements and then add all the children to the element except the THIS children (one click) to trigger the function?

This is a scary explanation, but I'm looking for something like this:

$(".block_header").click(function(){ $(".block_header span:not(this span)").toggleClass("collapse expand"); $(".container:not(this+div.container)").slideToggle(); }); 

Here is an example HTML:

 <h3 id="sender_header" class="block_header"><span>Sender</span></h3> <div id="sender_container" class="container"> <p>Show or hide this, based on which H3 is clicked.</p> </div> <h3 id="receiver_header" class="block_header"><span>Receiver</span></h3> <div id="receiver_container" class="container"> <p>Show or hide this, based on which H3 is clicked.</p> </div> <h3 id="delivery_header" class="block_header"><span>Delivery</span></h3> <div id="delivery_container" class="container"> <p>Show or hide this, based on which H3 is clicked.</p> </div> <h3 id="items_header" class="block_header"><span>Items</span></h3> <div id="items_container" class="container"> <p>Show or hide this, based on which H3 is clicked.</p> </div> .... etc, etc (many more of the same) 

Hope this is not too complicated. This will save me a lot of code.

+6
source share
4 answers

Instead of excluding an element in the selector, you can use the not() function, which takes a DOM element or jQuery object to remove from the jQuery set.

 $(".block_header").click(function(e) { $('.block_header span').not($(this).find('span')).toggleClass("collapse expand"); $('.container').not($(this).next()).slideToggle(); }); 
+14
source

Try the following:

 $(this).parent('h3').siblings('h3').children('span').addClass('active'); $(this).parent('h3').siblings('h3').next('div.container').slideToggle('active'); 

That should do the trick!

However, can I assume that you will have only one active?

If so, this is easiest:

 $('.active').removeClass('active').parent('h3').next('div.container').slideUp(); 

Hope that helps :)

change

To be smarter, keep active as a variable. So click:

 $active = $(this); 

Then, the next time you can do this without receiving jQuery to find the element again:

 $active.removeClass('active').parent('h3').next('div.container').slideUp(); $active = $(this); 
+3
source
 $(".block_header").click(function(){ $(".block_header span").not($('span', this)).toggleClass("active"); $(".container").not($(this).next()).slideToggle(); }); 
+2
source

Do it like

  $(".block_header").not(this).find("span").toggleClass("collapse","expand"); $(".container").not(this).not("div.container").slideToggle(); 
+1
source

Source: https://habr.com/ru/post/915780/


All Articles