Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the element before and after a specific element with pure javascript

Tags:

javascript

Having a list with links like this:

<ul>     <li><a href="#">First tab</a></li>     <li><a href="#">Second tab</a></li>     <li class="active"><a href="#">Active tab</a></li>     <li><a href="#">Fourth tab</a></li>     <li><a href="#">Fifth tab</a></li> </ul> 

How can be found element before and after the active tab? (In this case, the second and fourth tab).


I am looking for solution in pure JavaScript only, as jQuery solution is here.

Note: nextElementSibling and previousElementSibling are not supported by IE8 and FF3, so please post solutions that would be supported by those browsers as well. Thank you.

like image 947
Ωmega Avatar asked Jul 13 '12 17:07

Ωmega


1 Answers

Assuming your <ul> element is called element:

var active, prev, next; active = prev = next = element.querySelector('.active');  do prev = prev.previousSibling; while(prev && prev.nodeType !== 1); do next = next.nextSibling;     while(next && next.nodeType !== 1); 

This will work in Internet Explorer 8. If you're only worried about modern browsers:

var active = element.querySelector('.active'); var prev = active.previousElementSibling; var next = active.nextElementSibling; 
like image 59
Ry- Avatar answered Oct 14 '22 19:10

Ry-