Page 1 of 1

jQuery Question, Kieran?!? ;)

Posted: Fri Mar 23, 2007 1:50 am
by nickvd
I have the following jQuery code (heh, 1 'line', I love this library):

Code: Select all

$('.navSlide').find('a:eq(0)').click(function(){
      var grandPappy = this.parentNode.parentNode;
      $('dd',grandPappy).slideToggle('slow');
      return false;
}).end().find('dd').hide();
Which works perfectly against this html:

Code: Select all

<dl class="navSlide">
    <dt><a href="#">Info</a></dt>
    <dd>
        <a href="news.php">News</a>
        <a href="home/">Home Reno</a>
    </dd>
</dl>
The part that bugs me, is the this.parent.parent line. There has to be an easier (read: a jQuery) way to get the grandfather of the current element. To explain, inside the onClick function, 'this' is the <a> tag within the <dt>. I need to get back up to dl.navSlide so i only target the current element and not every single <dd> on the page.

I'm more or less fine with it as it is, but I am curious if there is a better way.

Oh, and jQuery rules! :)

Re: jQuery Question, Kieran?!? ;)

Posted: Fri Mar 23, 2007 2:25 am
by Kieran Huggins

Code: Select all

$('.navSlide').find('a:eq(0)').click(function(){
	  $(this).parents('.navSlide').children('dd').slideToggle('slow');
	  return false;
}).end().find('dd').hide();
the parents() function is what you seek - returns all parents of the current node that match the selector. While I was at it I condensed the code a little. I could have used find() in place of children(), but it doesn't matter in this case. I have no idea which is faster.
nickvd wrote:Oh, and jQuery rules! :)
Yes, yes it does ;)