Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I get the next element in HTML using JavaScript?(如何使用JavaScript获取HTML中的下一个元素?)

Suppose I have three <div> s and I get a reference to one in JavaScript code, I want to get which is the next <div> and which is the previous.(假设我有三个<div> ,我在JavaScript代码中得到一个引用,我想得到的是下一个<div> ,哪个是前一个。)   ask by Amr Elgarhy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
292 views
Welcome To Ask or Share your Answers For Others

1 Answer

use the nextSibling and previousSibling properties:(使用nextSiblingpreviousSibling属性:)

<div id="foo1"></div> <div id="foo2"></div> <div id="foo3"></div> document.getElementById('foo2').nextSibling; // #foo3 document.getElementById('foo2').previousSibling; // #foo1 However in some browsers (I forget which) you also need to check for whitespace and comment nodes:(但是在某些浏览器中(我忘了哪些)你还需要检查空格和注释节点:) var div = document.getElementById('foo2'); var nextSibling = div.nextSibling; while(nextSibling && nextSibling.nodeType != 1) { nextSibling = nextSibling.nextSibling } Libraries like jQuery handle all these cross-browser checks for you out of the box.(像jQuery这样的库可以为您提供开箱即用的所有这些跨浏览器检查。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...