Open In App

HTML DOM TreeWalker previousNode() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The TreeWalker previousNode() method moves the current Node to the previous visible node in the document order and returns the found node. If no such child exists in the document, this method returns null.

Syntax:

node = treeWalker.previousNode();

Parameters: This method takes no parameters.

Return Value:

  • Returns previous visible 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 previous visible node from the last child of body node of that TreeWalker 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.previousNode();
            console.log(node);
        }
    </script>
</body>
 
</html>


Output:

Before Clicking the Button:

After Clicking the Button: In the console, the previous visible child of the TreeWalker node that is <button> tag can be seen.

Supported Browsers: 

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

Last Updated : 11 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads