可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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: