Find element before and after specific element with pure javascript
Having a list with links like:
<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 I find an item before and after the active tab? (In this case, the second and fourth tabs).
I am only looking for a solution in pure JavaScript , as the jQuery solution is here .
Note. nextElementSibling and previousElementSibling not supported by IE8 and FF3, so submit solutions that will be supported by these browsers. Thanks.
+7
Ξ©mega
source share2 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 are only concerned about modern browsers:
var active = element.querySelector('.active'); var prev = active.previousElementSibling; var next = active.nextElementSibling; +16
Ryan
source sharePretty easy considering a modern browser:
var activeTab = document.getElementsByClassName('active')[0], activePrevSibling = activeTab.previousElementSibling, activeNextSibling = activeTab.nextElementSibling; JS Fiddle demo (with awful, awful colors ...).
The above edited based on the comment posted by Esailija:
document.querySelector(".active")more supported and compressed
var activeTab = document.querySelector('.active'), activePrevSibling = activeTab.previousElementSibling, activeNextSibling = activeTab.nextElementSibling; Literature:
+10
David thomas
source share