简体   繁体   中英

Understanding Crockford's walk_the_dom (“The Good Parts”)

I'm trying to work through to understand Crockford's walk_the_dom function below. Here is my logic and the DOM tree I am working with. I don't see when node.nextSibling is reached.

示例图

function walk(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        walk(node, func);
        node = node.nextSibling;
    }
};
  1. func(node) runs a function on the given node.
  2. node=node.firstChild() is now equal to the firstChild of document.body, or in this case, H1
  3. while(node) runs a loop where the walk function is run again.
  4. func(node) now runs a function on H1
  5. node = node.firstChild() is now equal to the firstChild of H1 , also known as #text in this case
  6. while(node) runs a loop where the walk function is run again
  7. func(node) runs a function on #text

  8. node = node.firstChild() --> what is the firstChild of #text ?

  9. when is node.nextSibling reached?

The firstChild of #text is null or undefined because there isn't any. JavaScript has what is known as truthy values. So while(null) is the same as while(false) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM