查找出现最多的 DOM 元素

Find DOM-element that occurs the most

本文关键字:DOM 元素 查找      更新时间:2023-09-26

容器div.example可以有不同的第一级子元素(section,div,ul,nav,...)。 这些元素的数量和类型可能会有所不同。

我必须找到出现最多的直接子项的类型(例如 div)。什么是简单的jQuery或JavaScript解决方案?

jQuery 1.7.1 是可用的,尽管它也应该在 IE <9 (array.filter) 中工作。

编辑:谢谢@Jasper,@Vega和@Robin马本:)

使用 .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/

编辑:我认为像下面这样的jQuery函数应该更有用。

演示

$.fn.theMostChild = function() {
    var childs = {};
    $(this).children().each(function() {
        if (childs.hasOwnProperty(this.nodeName)) {
            childs[this.nodeName] += 1;
        } else {
            childs[this.nodeName] = 1;
        }
    });
    var maxNode = '', maxNodeCount = 0;
    for (nodeName in childs) {
        if (childs[nodeName] > maxNodeCount) {
            maxNode = nodeName;
            maxNodeCount = childs[nodeName];
        }
    }
    return $(maxNode);
}

然后你可以,

$('div.example').theMostChild().css('color', 'red');

像下面的函数应该给你子元素的计数,你可以从中得到最大计数。见下文,演示

$(function () {
    var childs = {};
    $('div.example').children().each(function () {
        if (childs.hasOwnProperty(this.nodeName)) {
            childs[this.nodeName] += 1;
        } else {
            childs[this.nodeName] = 1;
        }
    });
    for (i in childs) {
        console.log(i + ': ' + childs[i]);
    }
});

如果没有有关预期子节点类型的一些信息,这是不可能的。

编辑:正如Jasper指出的那样,我们不需要事先知道标签名称。如果您仅在一组特定的选择器中查找,则以下内容有效。

var selectorArray = ['div', 'span', 'p',........]
var matches = $(div).children(selectorArray.join());    
var max = 0, result = [];    
$.each(selectorArray, function(i, selector){
    var l = matches.filter(selector).length;
    if(l > max){
     max = l;
     result[max] = selector;
    }
});

result[max]为您提供标记名称,max为您提供出现次数