を使用して子を繰り返し処理し、見つけたs.children()
の数をログに記録します。element.tagName
//create object to store data
var tags = {};
//iterate through the children
$.each($('#parent').children(), function () {
//get the type of tag we are looking-at
var name = this.tagName.toLowerCase();
//if we haven't logged this type of tag yet, initialize it in the `tags` object
if (typeof tags[name] == 'undefined') {
tags[name] = 0;
}
//and increment the count for this tag
tags[name]++;
});
これで、オブジェクトは、要素tags
の子として発生した各タイプのタグの番号を保持します。#parent
デモは次のとおりです。http://jsfiddle.net/ZRjtp/(コンソールでオブジェクトを監視します)
次に、最も多く発生したタグを見つけるには、次のようにします。
var most_used = {
count : 0,
tag : ''
};
$.each(tags, function (key, val) {
if (val > most_used.count) {
most_used.count = val;
most_used.tag = key;
}
});
オブジェクトは、最も使用されたタグとそのmost_used
使用回数を保持するようになりました。
これがデモです:http://jsfiddle.net/ZRjtp/1/