This is code from Crockford’s JavaScript: The Good Parts.
var results = [];
var walkDOM = function (node,func) {
func(node); //What does this do?
node = node.firstChild;
while(node) {
walkDOM(node,func);
node = node.nextSibling;
}
};
I understand the code except for func(node). I guess the point is to pass node as a parameter in function func, but how will the browser understand it this way? node and func could be anything–so when the function is called it could read like this:
walkDOM(document.body,function(att) {
node.getAttribute(att);
results.push(node);
});
When func is passed, walkDOM will process function(att) {…}(document.body)–which wouldn’t make any sense. So why has Crockford chosen to include func(node)?
Looks to me like the
funcis used for doing something to every node in the tree.For example, if I wanted to alert the tag name for every node in the entire tree:
In your example function:
… you have named the
nodeparameter toatt, but that doesn’t magically make in a name of an attribute. I would expect a “variable ‘node’ is not defined” whennode.getAttribute(att)is ran, because node is being set toatt… there is nonodein that function’s scope.