dynamic
dynamic

Reputation: 48141

jquery .next isn't 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 add the class box to let's say the last div generic:

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

Now if i try to select the next .box with this it doesnt' work:

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

returns .length=0

Upvotes: 3

Views: 634

Answers (2)

enoyhs
enoyhs

Reputation: 2069

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

And as lonesomeday said. You should use nextAll selector.

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 238045

I presume what you actually mean is #container div:last.

next does not find the next element that matches a selector. It finds the next sibling element. If you supply a selector, it tests the element against that selector. If the test fails, an empty selection (i.e. length == 0) is returned.

You need nextAll:

$('#secondbox').nextAll('.box').first();

Upvotes: 6

Related Questions