Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Parent Sibling selector

I have a HTML document like below:

<td>
  <div class="commentLink">
    <a href="javascript:ShowBox()">Show</a>
  </div>
  <div class="hiddenBox">
    <!-- Hidden content  -->
  </div>
</td>

The div element with class="hiddenBox" is hidden by default. On clicking the "Show" link, I want to show the hidden div. I tried this but it doesn't work:

function ShowBox() {
  $(function(){
    $(this).parent().siblings(".hiddenBox").show();
  });
}

The class hiddenBox occurs multiple times in my document, but I want only the sibling to show.

like image 305
K.R. Avatar asked Jul 05 '11 01:07

K.R.


1 Answers

The problem is that this in your function won't be the <a> element. You can change your inline handler like this to fix it:

<a href="#" onclick="ShowBox.call(this); return false;">Show</a>

Ah just noticed, additionally you'll need to reference the this outside of the ready handler.

function ShowBox() {
   var that = this;
   $(function(){
       $( that ).parent().siblings(".hiddenBox").show();
   });
}

I assume you've set it up this way in case someone clicks the link before the DOM is loaded.

like image 184
user113716 Avatar answered Sep 25 '22 14:09

user113716