Javascript 使用纯javascript查找特定元素之前和之后的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11475232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:59:16  来源:igfitidea点击:

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

javascript

提问by ?mega

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 JavaScriptonly, as jQuery solution is here.

我只在纯 JavaScript 中寻找解决方案,因为 jQuery 解决方案在这里

Note:nextElementSiblingand previousElementSiblingare not supported by IE8 and FF3, so please post solutions that would be supported by those browsers as well. Thank you.

注意:IE8 和 FF3 不支持nextElementSibling并且previousElementSibling不支持,因此请发布这些浏览器也支持的解决方案。谢谢你。

回答by Ry-

Assuming your <ul>element is called element:

假设您的<ul>元素被称为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:

这将适用于 Internet Explorer 8。 如果您只担心现代浏览器:

var active = element.querySelector('.active');
var prev = active.previousElementSibling;
var next = active.nextElementSibling;

回答by David says reinstate Monica

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, horriblecolours...).

JS Fiddle 演示(带有可怕的、可怕的颜色......)。



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

以上编辑,基于 Esailija 留下的评论:

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

document.querySelector(".active")更受支持和简洁

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

JS Fiddle demo.

JS小提琴演示

References:

参考: