Arnold de Jager
Arnold de Jager

Reputation: 107

Using javascript, how to select an li relative to a specific other li

Given the following html list:

<ul>
   ...
   <li>
   <li>    // <-- item to be selected
   <li>
   <li class='current'>
   <li>
   <li>
   <li>
   ...
</ul>

How do I select the li two instances ahead of the li with class current? Any pure javascript or jquery solution would be great!

Upvotes: 0

Views: 335

Answers (5)

Arnold de Jager
Arnold de Jager

Reputation: 107

I have accepted an answer. My own solution first identified the index of the element to be selected:

var index = $('.current').index()-n+1; 

n equals the number of items you want to be ahead of the current object. The +1 is because indexing starts at zero, yet nth-child at 1.

I then used the nth-child selector to get the right element:

$('ul li:nth-child('+index+')')

Upvotes: 0

skrtbhtngr
skrtbhtngr

Reputation: 2251

This may help...

var li=document.getElementsByTagName('li');
var i, n;
for(i=0;i<li.length;i++)
{
    if(li[i].className=='current')
    {
        n=(i+2)%(li.length);
    }
}
var x=li[n];

Upvotes: 2

PSL
PSL

Reputation: 123739

Making it more generic, i.e if you want to select a li possibly(2nd or 3rd or what ever instance that appears prior to your selector), then try

$('li.current').prevAll(':eq('  + n-1 + ')');

Here n would be the instance # that you are talking about (Since it is 0 based index). In your case this would be:

$('li.current').prevAll(':eq(1)');

Do remember that prevAll returns the elements in the order starting from the selector, so you can just provide the index of the element from that position in prevAll with eq selector.

Fiddle

Upvotes: 3

Satpal
Satpal

Reputation: 133403

You can try

$('.current').prev().prev()

Upvotes: 2

SLaks
SLaks

Reputation: 887275

Very easily:

$('.current').prev().prev()

Upvotes: 2

Related Questions