abc
abc

Jquery.next not working?

take this simple code:

<div id="container">

    <div class="box">abc</div>
    <div class="box" id="secondbox">abc</div>
    <div>generic</div>
    <div>generic</div>

</div>

Now I am adding a class field to say the last div:

$('#container div:last').addClass('box');

Now, if I try to select the following .box with this, it does not work:

$('#secondbox').next('.box')

returns .length = 0

+3
source share
2 answers

I guess what you really mean #container div:last.

nextdoes not find the next element that matches the selector. He finds the next element of sibling. If you supply a selector, it checks for an element on that selector. If the test fails, an empty selection is returned (i.e. length == 0).

You need to nextAll:

$('#secondbox').nextAll('.box').first();
+6
source

You must replace $('#container p:last').addClass('box');with$('#container div:last').addClass('box');

And as lonesomeday said. You must use the nextAll selector.

0
source

All Articles