views:

43

answers:

3
+1  Q: 

jquery selector

Hi,

I was wondering how I could use JQuery to select the child of a parent?

I have the following.

$("#navigation a.subpage").click(function () {
  $("#navigation ul ul")...

The HTML looks like this.

<li>
  <a class="subpage"...</a>
  <ul style="hidden">...</ul>
</li>

I need to somehow select the parents of the link. That would get me the relevant li. Then I need to select the ul and toggle it. How do I do this?

+3  A: 

Keep it simple:

$("a.subpage").click(function() {
  $(this).next().toggle();
  return false;
});

this in an event handler is the source of the event, being the link.

Edit: the issue of whether or not next() is appropriate. Of course if the markup is different you use a different chain. There are many ways of achieving the same result, for example:

$(this).siblings("ul").toggle();

But what if the link is inside a paragraph?

$(this).closest("li").children("ul").toggle();

But what if the list isn't a direct child?

Etc etc etc. All of these are reasonable approaches but keep it simple: Write your jQuery code to suit your markup rather than trying to cater for things that don't happen and probably never will.

cletus
Or you can keep the #navigation in the context of the selector for optimization: $("a.subpage", "#navigation").click(...
Kaaviar
I would prefer $(this).next('ul').toggle(); // takes care if some element is added in between.
mohang
The problem will remain if the added element between is another <ul> ;)
Kaaviar
@mohang: `.next()` doesn't work like this...I agree it's not intuitive, see my comment on the `.next()` documentation page: http://api.jquery.com/next/ You need `.nextAll('ul:first')` for that.
Nick Craver
*cough* `.closest()`!
Nick Craver
@Nick oh of course, fixed.
cletus
A: 

$(this).parent().find('ul').toggle()

sbmaxx
+3  A: 

If it's the next item always, then .next() works, if there may be something in-between use .siblings(), like this:

$("#navigation a.subpage").click(function() {
  $(this).siblings('ul').toggle();
  return false;
});

You can find the list of traversal functions here :)

Nick Craver