9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでDOMツリーの要素を数えあげる

Last updated at Posted at 2014-04-08

Chrome developer toolとかFirebugでDOMツリーの内容は見れるのですが、エレメント数をさくっと集計することはできなそうだったので、JSで実装しました。

JavaScriptコンソールにコピペして、

DOMTreeUtil.countTags(document.body);

などとすれば、引数のDOM要素以下をタグ名ごとに集計されます。
firefox addonとかchrome extensionとか探せばありそうだったな。

	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
    };
})();


9
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?