Open In App
Related Articles

HTML DOM previousSibling Property

Improve Article
Improve
Save Article
Save
Like Article
Like

The previousSibling property is used to return the previous node of the specified node as Node object or null if the specified node is the first in the list. It is a read-only property. 

Syntax:

node.previousSibling

Return value: This property returns a previous sibling of the specified node or null if the current node has no previous sibling. 

Example: In this example, we will use previousSibling property

HTML




<html>
 
<head>
    <title>DOM previousSibling Property</title>
</head>
 
<body style="text-align: center">
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h2>
        DOM previousSibling Property
    </h2>
    <div>
        <span id="p1">GeeksforGeeks! </span><span id="p2">
            A computer science portal for geeks.
        </span>
    </div>
    <br>
    <button onclick="geek()">Click me!</button>
    <br><br>
    <p id="p" style="margin:auto; width: 40%"></p>
    <!-- Function to return the previous node.-->
    <script>
        function geek() {
            let x = document.getElementById("p2")
                    .previousSibling.innerHTML;
            document.getElementById("p").innerHTML = x;
            document.getElementById("p").style.color = "white";
            document.getElementById("p").style.background = "green";
        }
    </script>
</body>
 
</html>


Output: 

 

Note: Don’t put whitespace between two sibling elements, else the result will be “undefined”. 

Supported Browsers: The browser supported by previousSibling property are listed below:

  • Google Chrome 1 and above
  • Edge 12 and above
  • Internet Explorer 5.5 and above
  • Firefox 1 and above
  • Opera 12.1 and above
  • Safari 1 and above

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 15 Jun, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials