Select all elements of a CSS class except $(this) with jQuery

Asked

Viewed 457 times

0

Be the HTML below as an example:

<div>
    <a class="link">Link 1</a>
    <a class="link">Link 2</a>
    <a class="link">Link 3</a>
<div>

How can I select all elements of a class except the element $(this) that I clicked on?

I’m trying to use the dial :not() CSS along with jQuery unsuccessfully:

$(".link").click(function(event) {
    $(".link" + ":not(" + $(this) + ")").hide(); // Isto não funciona
});

1 answer

3


You wouldn’t even need something like :not, just do the Hide and then the show just for the selected one, like this:

$(".link").click(function(event) {
    $(".link").hide();
    $(this).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<div>
    <a class="link">Link 1</a>
    <a class="link">Link 2</a>
    <a class="link">Link 3</a>
<div>

Now if you use with jQuery-ui and animations from it the effect will make it disappear and show this, which may even look like a bug, in this specific case you could just use the . filter so:

$(".link").click(function(event) {
    var $this = this;

    $(".link").filter(function (index, element) {
         return element !== $this;
    }).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<div>
    <a class="link">Link 1</a>
    <a class="link">Link 2</a>
    <a class="link">Link 3</a>
<div>

Or even easier, using the . not, like this:

$(".link").click(function(event) {
    $(".link").not(this).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<div>
    <a class="link">Link 1</a>
    <a class="link">Link 2</a>
    <a class="link">Link 3</a>
<div>

The filter would be more interesting for a more complex filtering, for your case . not already solves.


jQuery API:

  • 1

    WOW! Three ways! Thank you @Guilhermenascimento.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.