Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

My Solution to Tree Walker (nextNode)

90 views
Skip to first unread message

Robert Nantchouang Nantchouang

unread,
Nov 19, 2021, 10:52:46 AM11/19/21
to Intro to JavaScript
// Returns next node of DOM tree or null if no next node is found.
nextNode = function(node) {
  // Handles case for null input.
  if (node == null) {
    return null;
  }
  
  if (node.firstChild != null) {
    return node.firstChild;
  }

  if (node.nextSibling != null) {
    return node.nextSibling;
  }
  
  // If loop iterates back to the root, the DOM tree has no next node so it stops.
  while (node != null && node.nextSibling == null) {
    node = node.parentNode;
  }
  
  return node == null ? null : node.nextSibling;
};
Reply all
Reply to author
Forward
0 new messages