Wondering
Wondering

Reputation: 5096

meaning of this jquery code

I posted a question next() not working and gota reply which is working fine, but can somebody explain me what exactly is going on here:

$(this).closest('tr').next('tr').find("img.cc").toggle()
       .closest('tr').siblings('tr').find("img.cc").hide();

Upvotes: 1

Views: 482

Answers (4)

adardesign
adardesign

Reputation: 35781

This code is probably taken from in middle the context of a function

the first line says something like:

Starting from this (the element/s called on), Find the nearest (parent) tr then look for the next tr(meaning a brother of this parent) and find an img with the class of "cc" andtoggle its display value (meaning, if its visible then hide it and if its hidden show it.


The second line starts from where it finished, and says find a img with a class of "cc" in the siblings of the nearest (parent) tr's next tr and hide that it.

Upvotes: 1

jAndy
jAndy

Reputation: 236182

<tr>                              <<-- 1.)    <<-- 6.)
  <td>
    <a href="#" class="xx"></a>               <<-- we start here
  </td>
  <td>
    data
  </td>
</tr>
<tr>                              <<-- 2.)    <<--  5.)
  <td> 
    <img src="#" class="cc" />    <<-- 3.)    <<-- 4.)
  </td>
</tr>    
<tr>                              <<-- 6.)
  <td>
    <a href="#" class="xx"></a>
  </td>
  <td>
    data2
  </td>
</tr>
<tr>                              <<-- 6.)
  <td> 
    <img src="#" class="cc" />    <<-- 7.)
  </td>
</tr>
  • 1.) $(this).closest('tr')

    This line jumps to 1.)

  • 2.) .next('tr')

    We're arriving at 2.)

  • 3.) .find("img.cc")

    Now, we hopefully found element at 3.)

  • 4.) .toggle()

    We switch visibilty from element 4.) (visible/hidden)

  • 5.) .closest('tr')

    We jump back to the closest parent tr

  • 6.) siblings('tr')

    We receive all tr's marked with 6.)

  • 7.) .find("img.cc").hide();

    Find the img.cc within all siblings tr's -> 6.) and hide them.

Upvotes: 10

Nick Craver
Nick Craver

Reputation: 630627

It does the following, each step related to the method called:

  1. .closest('tr') - go from the current element up to the nearest <tr> ancestor (or itself, if it's already a <tr>).
  2. .next('tr') - go to the next sibling row
  3. .find("img.cc") - finds a <img class="cc"> inside that row
  4. .toggle() - toggle it (show if hidden, hide if shown)
  5. .closest('tr') - go back up to the <tr>
  6. .siblings('tr') - select all sibling (other) rows
  7. .find("img.cc") - find all the <img class="cc"> in them.
  8. .hide() - hide them

It could be a bite more efficient though using .end() to hop back in the chain, like this:

$(this).closest('tr').next('tr').find("img.cc").toggle()
       .end().siblings('tr').find("img.cc").hide();

Upvotes: 3

Svante Svenson
Svante Svenson

Reputation: 12478

Toggles visiblity of img.cc in the next table row and hides all other img.cc in the table.

Upvotes: 0

Related Questions