Jquery $(this) Child Selector

Orbalon picture Orbalon · May 8, 2009 · Viewed 228k times · Source

I'm using this:

jQuery('.class1 a').click( function() {
  if ($(".class2").is(":hidden")) {
    $(".class2").slideDown("slow");
  } else {
    $(".class2").slideUp();
  }
});

On page structure:

<div class="class1">
  <a href="...">text</a>
  <div class="class2">text</div>
</div>

It only works when you don't have multiple class1/class2 sets like:

<div class="class1">
  <a href="...">text</a>
  <div class="class2">text</div>
</div>
<div class="class1">
  <a href="...">text</a>
  <div class="class2">text</div>
</div>
<div class="class1">
  <a href="...">text</a>
  <div class="class2">text</div>
</div>

How do I change the initial jquery code so that it only effects class2 under the class1 that was clicked? I tried recommendations from How to get the children of the $(this) selector? but haven't succeeded.

Answer

Paolo Bergantino picture Paolo Bergantino · May 8, 2009

The best way with the HTML you have would probably be to use the next function, like so:

var div = $(this).next('.class2');

Since the click handler is happening to the <a>, you could also traverse up to the parent DIV, then search down for the second DIV. You would do this with a combination of parent and children. This approach would be best if the HTML you put up is not exactly like that and the second DIV could be in another location relative to the link:

var div = $(this).parent().children('.class2');

If you wanted the "search" to not be limited to immediate children, you would use find instead of children in the example above.

Also, it is always best to prepend your class selectors with the tag name if at all possible. ie, if only <div> tags are going to have those classes, make the selector be div.class1, div.class2.