How to get sibling elements in JavaScript?

In JavaScript getting the next or previous sibling are very straightforward. If we can get the element object then the object has nextElementSibling and previousElementSibling attributes. We can use to easily get the next or previous sibling elements.

Get next sibling element

<div id="parent">
    <div id="first">First child</div>
    <div id="second">Second child</div>
    <div id="third">Third child</div>
</div>


<script type="text/javascript">
    const element = document.getElementById('second');
    console.log(element.nextElementSibling);
</script>

Get previous sibling element

<div id="parent">
    <div id="first">First child</div>
    <div id="second">Second child</div>
    <div id="third">Third child</div>
</div>


<script type="text/javascript">
    const element = document.getElementById('second');
    console.log(element.previousElementSibling);
</script>