Open In App

HTML DOM TreeWalker parentNode() method

The TreeWalker parentNode() method moves the current Node to the first visible ancestor node or parent node of TreeWalker in the document order, and returns the found node. If no such child exists in the document, this method returns null.

Syntax:



node = treeWalker.parentNode();

Parameters: This method takes no parameters.

Return Value:



Example: In this example, create a TreeWalker with body node and hence showed the parentNode of that TreeWalker’s first node.




<!doctype html>
<html>
<head>
    <meta charset="utf-8">
<title>HTML DOM TreeWalker parentNode() method</title>   
</head>
<body>
    <h1>GeeksforGeeks</h1>
    <p>Click Below</p>
    <button onclick="get()">Click</button>
</body>
<script>
        var treeWalker = document.createTreeWalker(
        document.body,
        NodeFilter.SHOW_ELEMENT,
        { acceptNode: function(node) {
return NodeFilter.FILTER_ACCEPT; } },
        false
);
        function get(){
            treeWalker.firstChild();
            var node = treeWalker.parentNode();
            console.log(node);
        }
</script>
</html>

Output:

Before Button Click:

After Button Click: In console, the parentNode of the TreeWalker that is <body> tag can be seen.

Supported Browsers:

Article Tags :