0

I'm trying to use jQuery's next() to grab the very next paragraph of the selected element, but because there is a div in the way, it seems as though next will not work. What selector should I be using instead?

Works :

<div>
   <span class="clickme">A name here</span>
   <p class="showme" style="display:none;">Here's some text! </p>
</div>
$('.clickme').click(function() {
   $(this).next('.showme').slideDown();
});

Does not work :

<div>
   <span class="clickme">A name here</span>
   <div></div>
   <p class="showme" style="display:none;">Here's some text! </p>
</div>
$('.clickme').click(function() {
   $(this).next('.showme').slideDown();
});

Why does this occur? Does next() with a specified class not go beyond the very next block element? Is that why this is happening? Is there a selector that specify the very 'next' class with showme should be selected?

Fiddle - http://jsfiddle.net/QespX/

2 Answers 2

3

.next(): Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

.nextAll():Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.

So this is how you go

$('.clickme').click(function() { 
    $(this).nextAll('.showme').slideDown();   //as clickme>showme
});

More information about Tree Traversal can be found out at jQuery API Documentation.

0
1

You can use .nextAll():

$('.clickme').click(function() {
    $(this).nextAll('.showme').slideDown();
});

Demo: http://jsfiddle.net/QespX/1/

The only reason this works is because .showme is a sibling of .clickme. .nextAll() will select all of the .showMe elements after your clicked element, but since you have only one, it'll work.

If that's a problem, you can use .first() to narrow the results down:

$(this).nextAll('.showme').first().slideDown();
4
  • Ahhhh, so if that's the case, could I use $(this).sibling('.showme') instead? Would that be more ideal?
    – RCNeil
    Feb 14, 2013 at 20:44
  • @RCNeil: There's only .siblings(), which is just like .nextAll() but it searches in both directions. I don't really know why jQuery's .next() doesn't find the next element like you would expect.
    – Blender
    Feb 14, 2013 at 20:45
  • Ah. Many thanks @Blender! Actually, since there will be more elements, it actually seems like siblings() is a more appropriate selector in this case. Appreciate the answer!
    – RCNeil
    Feb 14, 2013 at 20:48
  • p.s. the only reason I marked the other answer is because I like giving rep to the less fortunate. Your answer really did provide the insight I needed for my code.
    – RCNeil
    Feb 14, 2013 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.