Get next / previous element using JavaScript?

Amr Elgarhy picture Amr Elgarhy · Feb 22, 2009 · Viewed 294.1k times · Source

How do I get the next element in HTML using JavaScript?

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.

Answer

Crescent Fresh picture Crescent Fresh · Feb 22, 2009

use the nextSibling and previousSibling properties:

<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.