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