Created
April 8, 2014 16:43
-
-
Save sugarshin/10153871 to your computer and use it in GitHub Desktop.
DOM Element数える
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var DOMTreeUtil = (function() { | |
var visitAll = function(root, func) { | |
_visit(root, func); | |
}; | |
var _visit = function(elem, func) { | |
if (!elem.hasChildNodes) return; | |
var i, l; | |
var child = elem.childNodes; | |
for (i = 0, l = child.length; i < l; i++) { | |
func(child[i]); | |
_visit(child[i], func); | |
} | |
}; | |
var countTags = function(root) { | |
var result = {}; | |
visitAll(root, function(elem) { | |
if (elem.nodeType == Node.TEXT_NODE) { | |
if (!result['text']) { | |
result['text'] = 0; | |
} | |
result['text']++; | |
} | |
else if (!result[elem.tagName]) { | |
result[elem.tagName] = 1; | |
} else { | |
result[elem.tagName]++; | |
} | |
}); | |
return result; | |
}; | |
return { | |
visitAll: visitAll, | |
countTags: countTags | |
}; | |
})(); | |
DOMTreeUtil.countTags(document.body); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment