Recursion down DOM tree

前端 未结 4 1789
暖寄归人
暖寄归人 2020-12-13 16:59

This is code from Crockford\'s JavaScript: The Good Parts.

var results = [];

var walkDOM = function (node,func) {
        func(node);                     //         


        
4条回答
  •  不思量自难忘°
    2020-12-13 17:12

    Yes this tree traversal function makes sense since :

    • the function argument is supposed to know how to handle (any) nodes
    • the first call argument is supposed to be a supported node (not document.body for instance, if func doesn't know how to handle it)

    That said, this algorithm still looks incorrect to me, as it only explores through the first sibling ; other siblings will be simply ignored. So I would recommend using this more traditional approach instead :

    function walk(node, func) {
       var children = node.childNodes;
       for (var i = 0; i < children.length; i++)  // Children are siblings to each other
           walk(children[i], func);
       func(node);
    }
    

    Note that version is "deep first" (i.e. not calling call func() before processing children), but I'd rather recommend it since func is likely to change nodes. This way the processing of a parent will be able to consider the latest state of its already-processed children before issuing possibly un-appropriate changes.

提交回复
热议问题