Open In App

HTML DOM TreeWalker previousSibling() Method

Last Updated : 13 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The TreeWalker previousSibling() method moves the current Node to its previous sibling if any and returns the found sibling. If no such child exists in the document, this method returns null.

Syntax:

node = treeWalker.previousSibling();

Parameters: This method takes no parameters.

Return Value:

  • Returns previously visible sibling of the current node if exists.
  • Returns null if no such child exists.

Example: In this example, a TreeWalker with body node is created and hence showed the previously visible sibling of that TreeWalker’s last node.

HTML




<!DOCTYPE html>
<html>
 
<body>
    <h1>GeeksforGeeks</h1>
 
     
<p>Click Below</p>
 
 
    <button onclick="get()">Click</button>
 
    <script>
        var treeWalker = document
            .createTreeWalker(document.body,
            NodeFilter.SHOW_ELEMENT, {
                acceptNode: function (node)
                { return NodeFilter.FILTER_ACCEPT; }
            },
            false
        );
        function get() {
            treeWalker.lastChild();
            var node = treeWalker.previousSibling();
            console.log(node)
        }
    </script>
</body>
 
</html>


Output:

Before Clicking the Button:

After Clicking the Button: In the console, the previous visible sibling of the body’s last element of the TreeWalker node that is <button> can be seen.

Supported Browsers:

  • Google Chrome 1
  • Edge 12
  • Firefox 4
  • Safari 3
  • Opera 9
  • Internet Explorer 9

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads