First tab
  • 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
    source share
    2 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
    source

    Pretty 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; 

    JS Fiddle demo .

    Literature:

    +10
    source

    All Articles