Get next / previous element using JavaScript?

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.



Well in pure javascript my thinking is that you would first have to collate them inside a collection.

var divs = document.getElementsByTagName("div");
//divs now contain each and every div element on the page
var selectionDiv = document.getElementById("MySecondDiv");

So basically with selectionDiv iterate through the collection to find its index, and then obviously -1 = previous +1 = next within bounds

for(var i = 0; i < divs.length;i++)
   if(divs[i] == selectionDiv)
     var previous = divs[i - 1];
     var next = divs[i + 1];

Please be aware though as I say that extra logic would be required to check that you are within the bounds i.e. you are not at the end or start of the collection.

This also will mean that say you have a div which has a child div nested. The next div would not be a sibling but a child, So if you only want siblings on the same level as the target div then definately use nextSibling checking the tagName property.


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.


Really depends on the overall structure of your document.

If you have:


it may be as simple as traversing through using


However, if the 'next' div could be anywhere in the document you'll need a more complex solution. You could try something using


and running through these to get where you want somehow.

If you are doing lots of complex DOM traversing such as this I would recommend looking into a library such as jQuery.


There is a attribute on every HTMLElement, "previousElementSibling".


<div id="a">A</div>
<div id="b">B</div>
<div id="c">c</div>

<div id="result">Resultado: </div>

var b = document.getElementById("c").previousElementSibling;

document.getElementById("result").innerHTML += b.innerHTML;



This will be easy... its an pure javascript code


all these solutions look like an overkill. Why use my solution?

previousElementSibling supported from IE9

document.addEventListener needs a polyfill

previousSibling might return a text

Please note i have chosen to return the first/last element in case boundaries are broken. In a RL usage, i would prefer it to return a null.

var el = document.getElementById("child1"),
    children = el.parentNode.children,
    len = children.length,
    ind = [], el),
    nextEl = children[ind === len ? len : ind + 1],
    prevEl = children[ind === 0 ? 0 : ind - 1];
<div id="parent">
  <div id="child1"></div>
  <div id="child2"></div>


Tested it and it worked for me. The element finding me change as per the document structure that you have.

        <script type="text/javascript" src="test.js"></script>
        <form method="post" id = "formId" action="action.php" onsubmit="return false;">
                        <label class="standard_text">E-mail</label>
                    <td><input class="textarea"  name="mail" id="mail" placeholder="E-mail"></label></td>
                    <td><input class="textarea"  name="name" id="name" placeholder="E-mail">   </label></td>
                    <td><input class="textarea"  name="myname" id="myname" placeholder="E-mail"></label></td>
                    <td><div class="check_icon icon_yes" style="display:none" id="mail_ok_icon"></div></td>
                    <td><div class="check_icon icon_no" style="display:none" id="mail_no_icon"></div></label></td>
                    <td><div class="check_message" style="display:none" id="mail_message"><label class="important_text">The email format is not correct!</label></div></td>
            <input class="button_submit" type="submit" name="send_form" value="Register"/>


var inputs;
document.addEventListener("DOMContentLoaded", function(event) {
    var form = document.getElementById('formId');
    inputs = form.getElementsByTagName("input");
    for(var i = 0 ; i < inputs.length;i++) {
        inputs[i].addEventListener('keydown', function(e){
            if(e.keyCode == 13) {
                var currentIndex = findElement(
                if(currentIndex > -1 && currentIndex < inputs.length) {

function findElement(element) {
    var index = -1;
    for(var i = 0; i < inputs.length; i++) {
        if(inputs[i] == element) {
            return i;
    return index;


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.