jQuery Question, Kieran?!? ;)

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
nickvd
DevNet Resident
Posts: 1027
Joined: Thu Mar 10, 2005 5:27 pm
Location: Southern Ontario
Contact:

jQuery Question, Kieran?!? ;)

Post 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! :)
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: jQuery Question, Kieran?!? ;)

Post 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 ;)
Post Reply