jQuery selector not this child

Richard Harris picture Richard Harris · May 15, 2012 · Viewed 22.8k times · Source

Is there any way to attach a click event to several elements, and then have all children to the element, except children of THIS (the one clicked), to run a function?

That's a terrible 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's a sample 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 isn't too complicated. It would save me a LOT of code.

Answer

Matt picture Matt · May 15, 2012

Rather than excluding the element in the selector, you can use the not() function, which accepts 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();
});