How can I exclude $(this) from a jQuery selector?

JqueryJquery SelectorsThis

Jquery Problem Overview


I have something like this:

<div class="content">
    <a href="#">A</a>
</div>
<div class="content">
    <a href="#">B</a>
</div>
<div class="content">
    <a href="#">C</a>
</div>

When one of these links is clicked, I want to perform the .hide() function on the links that are not clicked. I understand jQuery has the :not selector, but I can't figure out how to use it in this case because it is necessary that I select the links using $(".content a")

I want to do something like

$(".content a").click(function()
{
    $(".content a:not(this)").hide("slow");
});

but I can't figure out how to use the :not selector properly in this case.

Jquery Solutions


Solution 1 - Jquery

Try using the not() method instead of the :not() selector.

$(".content a").click(function() {
    $(".content a").not(this).hide("slow");
});

Solution 2 - Jquery

You can use the not function rather than the :not selector:

$(".content a").not(this).hide("slow")

Solution 3 - Jquery

You can also use the jQuery .siblings() method:

HTML

<div class="content">
  <a href="#">A</a>
  <a href="#">B</a>
  <a href="#">C</a>
</div>

Javascript

$(".content").on('click', 'a', function(e) {
  e.preventDefault();
  $(this).siblings().hide('slow');
});

Working demo: http://jsfiddle.net/wTm5f/

Solution 4 - Jquery

You should use the "siblings()" method, and prevent from running the ".content a" selector over and over again just for applying that effect:

HTML

<div class="content">
    <a href="#">A</a>
</div>
<div class="content">
    <a href="#">B</a>
</div>
<div class="content">
    <a href="#">C</a>
</div>

CSS

.content {
    background-color:red;
    margin:10px;
}
.content.other {
    background-color:yellow;
}

Javascript

$(".content a").click(function() {
  var current = $(this).parent();
  current.removeClass('other')
    .siblings()
    .addClass('other');
});

See here: http://jsfiddle.net/3bzLV/1/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLogan SermanView Question on Stackoverflow
Solution 1 - JqueryDan HerbertView Answer on Stackoverflow
Solution 2 - JqueryZach LangleyView Answer on Stackoverflow
Solution 3 - JqueryEdgar OrtegaView Answer on Stackoverflow
Solution 4 - JqueryRonen CypisView Answer on Stackoverflow