Get next / previous element using JavaScript?

JavascriptHtmlDom

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Really depends on the overall structure of your document.

If you have:

<div></div>
<div></div>
<div></div>

it may be as simple as traversing through using

mydiv.nextSibling;
mydiv.previousSibling;

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

document.getElementsByTagName("div");

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Ex:

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

Live: http://jsfiddle.net/QukKM/

Solution 5 - Javascript

Its quite simple. Try this instead:

let myReferenceDiv = document.getElementById('mydiv');
let prev = myReferenceDiv.previousElementSibling;
let next = myReferenceDiv.nextElementSibling;

Solution 6 - Javascript

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

    <script>
           alert(document.getElementById("someElement").previousElementSibling.innerHTML);
    </script>

Solution 7 - Javascript

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 = [].indexOf.call(children, el),
    nextEl = children[ind === len ? len : ind + 1],
    prevEl = children[ind === 0 ? 0 : ind - 1];
    
    document.write(nextEl.id);
    document.write("<br/>");
    document.write(prevEl.id);

<div id="parent">
  <div id="child1"></div>
  <div id="child2"></div>
</div>

Solution 8 - Javascript

You can use nextElementSibling or previousElementSibling properties

<div>
    <span id="elem-1">
        span
    </span>
</div>
<div data-id="15">
    Parent Sibling
</div>


const sp = document.querySelector('#elem-1');
let sibling_data_id = sp.parentNode.nextElementSibling.dataset.id;
console.log(sibling_data_id); // 15

Solution 9 - Javascript

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

<html>
    <head>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body>
        <form method="post" id = "formId" action="action.php" onsubmit="return false;">
            <table>
                <tr>
                    <td>
                        <label class="standard_text">E-mail</label>
                    </td>
                    <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>
                </tr>
            </table>
            <input class="button_submit" type="submit" name="send_form" value="Register"/>
        </form>
    </body>
</html>

 

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(e.target)
                if(currentIndex > -1 && currentIndex < inputs.length) {
                    inputs[currentIndex+1].focus();
                }
            }	
        });
    }
});

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

Solution 10 - Javascript

that's so simple

var element = querySelector("div")
var nextelement = element.ParentElement.querySelector("div+div")

Here is the browser supports https://caniuse.com/queryselector

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmr ElgarhyView Question on Stackoverflow
Solution 1 - JavascriptCrescent FreshView Answer on Stackoverflow
Solution 2 - JavascriptAndy HumeView Answer on Stackoverflow
Solution 3 - JavascriptREA_ANDREWView Answer on Stackoverflow
Solution 4 - Javascriptuser1970894View Answer on Stackoverflow
Solution 5 - JavascriptI'm WevertonView Answer on Stackoverflow
Solution 6 - JavascriptsmurfView Answer on Stackoverflow
Solution 7 - JavascriptRafael HerscoviciView Answer on Stackoverflow
Solution 8 - JavascriptHarut EnoqyanView Answer on Stackoverflow
Solution 9 - JavascriptNitin MisraView Answer on Stackoverflow
Solution 10 - JavascriptMert ÇelikView Answer on Stackoverflow