100

Advanced title, simple question:

How can I do the following in jQuery (hiding everything except $(this))?

$("table tr").click(function() {
    $("table tr:not(" + $(this) + ")").hide();
    // $(this) is only to illustrate my problem

    $("table tr").show();
});
Kordonme
  • 2,314
  • 3
  • 20
  • 32

4 Answers4

195
$(this).siblings().hide();

Traversing/Siblings

Alex Gyoshev
  • 11,929
  • 4
  • 44
  • 74
159
$("table.tr").not(this).hide();

As an aside, I think you mean $("table tr") (with a space instead of a dot).
The way you have it, it selects every table which has a class of tr (eg, <table class="tr">), which is probably not what you want.

For more information, see the documentation.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Yeah, it was a mistake with the dot. I somehow fail to see how this is easier than Alexanders solution, which seems more clean. I know i asked how to do it with :not, but the siblings method just seems more clean. – Kordonme Aug 26 '09 at 06:13
  • 3
    Just to add, if you're clicking something within the table to try and get it to hide all the table rows EXCLUDING the row containing the item you clicked, use: `$('tr').not($(this).closest('tr')).hide();` – Jimbo Jan 18 '13 at 12:54
  • 3
    This is useful for selecting specific elements, in case the structure is more complex than siblings would allow. I'm having a hard time coming up with an example, but perhaps something where you want to hide things inside a grid, but not the grid itself. – goodeye Feb 28 '13 at 02:01
8

If you want to combine not() with some other selectors, you can use add():

$('a').click(function(e){
  $('a').not(this).add('#someID, .someClass, #someOtherID').animate({'opacity':0}, 800);
});

This would fadeout all other links, but the clicked one, and additionally fadeout some chosen ids and classes.

lenooh
  • 10,364
  • 5
  • 58
  • 49
0

I think a solution can be this:

$("table.tr").click(function() {
    $("table.tr:not(" + $(this).attr("id") + "").hide(); // $(this) is only to illustrate my problem
    $(this).show();
})

--EDIT for Comment:

$("table.tr").click(function() {
    $("table.tr:not(#" + $(this).attr("id") + ")").hide(); // $(this) is only to illustrate my problem
    $(this).show();
})
andres descalzo
  • 14,887
  • 13
  • 64
  • 115
  • You mean `:not(#" + ...`. Also, this won't work unless the element has an ID, which is unlikely. – SLaks Aug 25 '09 at 13:51
  • 3
    this would require you to add random and unnecessary ids onto all your table rows (or whatever you're using). – nickf Aug 25 '09 at 13:53
  • @ SLaks, Thanks for the correction. On the dow, you may have in mind that sometimes what we seek is to have a Quick Answers to help. Why not take lightly what we put. – andres descalzo Aug 25 '09 at 13:55
  • @nickf, Yes, you're right, but that comment would be good first asking a @Kordonme if they have ID for each TR. – andres descalzo Aug 25 '09 at 14:05