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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With