Search code examples
javascriptdom-traversal

Why does TreeWalker currentNode default to root node?


When constructing a TreeWalker, why does the currentNode point to the root, even though it may not pass filter criteria?

I would have expected it to be null, until I call nextNode, so that I can see if the root is passing filter criteria passed to it.

I guess it's the way its designed, I just don't quite understand the reason. It doesn't fit my use case of finding all elements with a particular attribute set, including the root. If I go up to the parent of the root, I'm including siblings I don't want.


Solution

  • The current node does not represent the result of the last method call, but it denotes the current state of the walk, the node from which the next step is made. It must never be null, and indeed might be a node that would not pass the filter - it can be set arbitrarily (manually, not only by the step methods).

    Only the return values of all the method calls will be filtered nodes, and those can be null.

    It doesn't fit my use case of finding all elements with a particular attribute set, including the root.

    Using the parentNode method should eventually get you to the root node if it matches the filter, or null otherwise.