sibling of a list element in JavaScript?


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

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.

Live Demo

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

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.

Live Demo

<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
raja
Published on 09-Aug-2019 15:38:08
Advertisements