To find the sibling of a list element javascript has provided a method called node.nextSibling. If we know any member of a list we can find its sibling. Let's discuss it in a nutshell.
syntax
node.nextSibling;
Example
In the following example, there are 3 list elements. Using the nextSibling property the sibling of the first element is found out and displayed the result in the output.
<html> <body> <ul><li id="item1">Tesla</li><li id="item2">Spacex</li><li id="item3">Solarcity</li></ul> <p id="next"></p> <script> var x = document.getElementById("item1").nextSibling.innerHTML; document.getElementById("next").innerHTML = "The sibling element is "+" "+x; </script> </body> </html>
Output
Tesla Spacex Solarcity The sibling element is Spacex
Example
In the following example, there are 3 list elements. Using the nextSibling property the sibling of the second element is found out and displayed the result in the output. The sibling element is nothing but the next element of the target element.
<html> <body> <ul><li id="item1">Tesla</li><li id="item2">Spacex</li><li id="item3">Solarcity</li></ul> <p id="next"></p> <script> var x = document.getElementById("item2").nextSibling.innerHTML; document.getElementById("next").innerHTML = "The sibling element is "+" "+x; </script> </body> </html>
Output
Tesla Spacex Solarcity The sibling element is Solarcity