JavaScript Get Next Sibling of an HTML Element

To get the next sibling of a specific HTML Element, using JavaScript, get reference to this HTML element, and read the nextElementSibling property of this HTML Element.

nextElementSibling property returns the element immediately following this HTML element.

In the following example, we will get the next sibling of the HTML Element, where the HTML element is selected by id "myElement". We shall change the font color of the next sibling.

example.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <h2>Get Next Sibling of HTML Element using JavaScript</h2>
    <div id="myElement" style="border:1px solid">
        <p>HTML Element Part 1.</p>
        <p>HTML Element Part 2.</p>
    </div>
    <p>Hello World!</p>
    <br>
    <button type="button" onclick="execute()">Click Me</button>
    <script>
    function execute(){
        var element = document.getElementById('myElement');
        var sibling = element.nextElementSibling;
        sibling.style.color = "red";
    }
    </script>
</body>
</html>

Try this html file online, and click on the Click Me button. The script gets the next sibling of the HTML Element #myElement, and changes its color to red.

Conclusion

In this JavaScript Tutorial, we learned how to get the next sibling element of an HTML Element, using JavaScript.