2

I have the following HTML structure and JavaScript file:

.html

<li>
 <button class="show-more"></button>
 some more elements
 <div class="hidden"></div>
</li>

JavaScript

$( ".show-more" ).click(function() {
  event.preventDefault();
  $( this ).next().slideToggle( "fast", function() {
  });
});

I need the click event to toggle the next first instance of .hidden, however the click event is targeting the first element after it and not the next instance of .hidden, any ideas how I can go about it?

Julian Samarjiev
  • 479
  • 1
  • 8
  • 23
  • 2
    Note: you have to pass `event` as a parameter to callback-function of `.click` in order to use `event.preventDefault();` – empiric Jun 22 '15 at 08:21
  • Note @empiric's very good catch there: As it is, your code is relying on a *global* `event` object, and relying on it having the `preventDefault` method. It will work on modern IE and Chrome, but will fail on Firefox (doesn't have a global `event`) and older IE (does, but that event doesn't have `preventDefault`). – T.J. Crowder Jun 22 '15 at 08:25

2 Answers2

6

nextAll and first:

$(this).nextAll('.hidden').first().slideToggle(...);

This question has more about this: Efficient, concise way to find next matching sibling?

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Another possible solution:

$('~.hidden:first', this).slideToggle("fast");

This will match for the first, next sibling of the class .hidden in the context of this. The ~-selector will reach all following siblings.

Demo

Reference

Next sibling selector

first selector

context of selector

empiric
  • 7,825
  • 7
  • 37
  • 48