Created
April 8, 2014 13:53
-
-
Save kumabook/10127542 to your computer and use it in GitHub Desktop.
JavaScriptでDOMツリーの要素を数えあげる ref: http://qiita.com/kumabook/items/6d3e48108029f309ebbd
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 | |
}; | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment