zedouard
zedouard

Reputation: 255

How to get next with JQuery out of ancestor

I want the next 'a' element of current 'a'. When current is 2,3,4 I catch 3,4,5 with a $('a.current').nextAll('a') but when current is 5 i can't catch the next 'a'. If someones has the solution...

<div id="slides">
    <ul>
     <li>
        <a href="" class='current'>2</a>
        <a href="" >3</a>
        <a href="" >4</a>
        <a href="" >5</a>
     </li>
      <li>
        <a href="" >6</a>
        <a href="" >7</a>
        <a href="" >8</a>
        <a href="" >9</a>
     </li>
    </ul>
</div>

Upvotes: 0

Views: 130

Answers (5)

veeTrain
veeTrain

Reputation: 2915

If you are able to know that you are at the end (no results), then you should be able to jump out into the next li and grab all the subsequent anchor elements.

Here's how I approached it. I gave the fifth anchor element an id to indicate it was my current. When your current target has no .nextAll() children (a .size() of 0), you could execute the following to find the subsequent anchor elements.

$("#5").parent().next("li").find("a").css("color","grey");​

The color change is to assist in indicating which elements were found. Looks like you have lots of options to choose between!

Update: If you just want the first one, you could capture it with the :first designation like this update.

$("#5").parent().next("li").find("a:first")

Upvotes: 0

cliffs of insanity
cliffs of insanity

Reputation: 3694

var curr = $('a.current'),            // get the current
    a = curr.closest('ul').find('a'), // get all the "a" elements
    idx = a.index(curr),              // get the index of the current among all
    nextall = a.slice(idx + 1);       // slice those greater than the current

live demo: http://jsfiddle.net/eaXdc/


If you only wanted the next one, change this:

a.slice(idx + 1);

to this:

a.eq(idx + 1);

Upvotes: 1

adeneo
adeneo

Reputation: 318302

var next = $(this).index() < $(this).parent().children('a').length-1 ? 
           $(this).next() : 
           $(this).parent().next('li').children('a:first');

FIDDLE

Upvotes: 1

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

Because .nextAll() returns only the siblings of matched elements

6,7,8,9 are not sibling of 5 as they are under different parent(li)

You you need those you have to traverse the DOM using jQuery to fetch those a elements.

Upvotes: 0

jmar777
jmar777

Reputation: 39659

Try this:

var $curr = $('a.current'),
    $next = $curr.next('a');

$next.length || ($next = $curr.parent().next().find('a:first'));

Also, you're currently using nextAll, which will return ALL of the following a elements, when it sounds like you want just the first following a.

Upvotes: 1

Related Questions