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

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

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.

回答1:

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; 


回答2:

Pretty easily, given an up-to-date browser:

var activeTab = document.getElementsByClassName('active')[0],     activePrevSibling = activeTab.previousElementSibling,     activeNextSibling = activeTab.nextElementSibling; 

JS Fiddle demo (with horrible, horrible colours...).


The above edited, based on the comment left by Esailija:

document.querySelector(".active") is more supported and concise

var activeTab = document.querySelector('.active'),     activePrevSibling = activeTab.previousElementSibling,     activeNextSibling = activeTab.nextElementSibling; 

JS Fiddle demo.

References:



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!