Recursion down DOM tree

前端 未结 4 1790
暖寄归人
暖寄归人 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:10

    Crockford's code is passing a callback to walkDOM which can be used in many ways to process the arguments passed to it.

    An example could be a method which returns the count of all DOM elements with the specified tagName:

    var getTagNameCount = function(tagName) {
        var count = 0;
        walkDOM(document.body, function(node) {
           if (node.tagName === tagName) {
              count++;
           }
        });
        return count;
    };
    

提交回复
热议问题