Open In App

HTML DOM TreeWalker nextSibling() method

Last Updated : 11 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

Syntax:

node = treeWalker.nextSibling();

Parameters: This method takes no parameters.

Return Value:

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

Example: In this example, I have created a TreeWalker with body node and hence showed the next visible sibling of that TreeWalker’s first node.

html




<!doctype html>
<html>
<head>
    <meta charset="utf-8">
<title>HTML DOM TreeWalker nextSibling() 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.nextSibling();
            console.log(node)
        }
</script>
</html>


Output:

Before Button Click:

After Button Click: In console, the next visible sibling of  body’s first element of the TreeWalker node that is <p> 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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads