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.


<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <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>
    <p>Hello World!</p>
    <button type="button" onclick="execute()">Click Me</button>
    function execute(){
        var element = document.getElementById('myElement');
        var sibling = element.nextElementSibling; = "red";
Try Online

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.

JavaScript - Get Next Sibling of an HTML Element


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