0

It works:

<div class="xpav">
    Create
</div>
<div class="apr" style="display: none;">
    sometext
</div>

<script>
$('.xpav').click(function() {
    $(this).next(".apr").slideDown("fast");    
})
</script>

It doesn't:

<div class="xpav">
    Create
</div>
<br />
<div class="apr" style="display: none;">
    sometext
</div>

<script>
$('.xpav').click(function() {
    $(this).next(".apr").slideDown("fast");    
})
</script>

Why
breaks it?

5 Answers 5

7

.next() only looks at the element that comes after the given element, then checks that element against the selector if it's provided. In your second example, since the br is there and doesn't have the apr class, it isn't picked up. From the API docs:

Description: 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.

Your second example requires the use of .nextAll() instead to search through all the next siblings:

$('.xpav').click(function() {
    $(this).nextAll(".apr").slideDown("fast");    
});

To pick up only the first .apr that's matched, use .eq(0):

$('.xpav').click(function() {
    $(this).nextAll(".apr").eq(0).slideDown("fast");    
});
1

under my impression next() only works if the sibling objuect is the same DOM tage,

what does work is:

$('.xpav').click(function() {
    console.log($(this).next(".apr"));
    $(this).siblings(".apr").slideDown("fast");    
})
1

It's exactly that what the documentations says: "Description: 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."

http://api.jquery.com/next/

0

Because next() takes you to the immediate next DOM element which is <br />. Why not use this:

$(".apr").slideDown("fast");

1
  • 1
    Because then every single .apr will animate?
    – BoltClock
    Apr 18, 2011 at 18:09
0

Simply because you are using the next() method in your code. The next DOM element from $('.xpav') in the second version of your code is a <br />, and since that doesn't match the filter, it doesn't slide anything down!

If you want it to work, you should consider using nextAll() instead of next(), as the latter ONLY gets the very next DOM element, where the former gets all siblings that are after itself in the DOM.

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.