Search code examples
jquerycss-selectorsparent

jquery selector: how can I use JQuery to select the child of a parent?


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?


Solution

  • 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.