JavaScript Get Previous Sibling of an HTML Element

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

previousElementSibling property returns the element immediately prior to this HTML element.

Example

In the following example, we will get the previous sibling of the HTML Element, where the HTML element is selected by id "myElement". Once we get the previous sibling, we will change its color to red.

example.html

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

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

Conclusion

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