我如何通过jQuery获取最多标签的div

时间:2012-10-24 12:08:55

标签: jquery html

我想通过jQuery搜索我的HTML代码,以获得具有最多HTML标记的div。在下面的例子中,jQuery应该返回#div2,因为它里面包含4个div。

<div id="div1">
    <div>content</div>
    <div>content</div>
    <div>content</div>
</div>
<div id="div2">
    <div>content</div>
    <div>content</div>
    <div>content</div>
    <div>content</div>
</div>
<div id="div3">
    <div>content</div>
    <div>content</div>
</div>

很抱歉,如果这个例子有点含糊不清 - 我认为不需要非常具体的代码块。提前谢谢。

3 个答案:

答案 0 :(得分:12)

您可以iterating through each divkeeping the div with maximum childs

执行此操作

<强> Live Demo

maxChild = 0;
maxChildDiv = null;

$('div').each(function(){
    currentChildCount = $(this).children().length 
    if(currentChildCount > maxChild ) 
    {
        maxChild = currentChildCount ;
        maxChildDiv = $(this);
    } 
});

答案 1 :(得分:2)

这对我有用: -

<html>
    <head>
        <title>test</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script>

$(document).ready(function() {
    max = 0;
    divid = null;

    $('div').each(function() {
        if($(this).children().length > max) {
            max = $(this).children().length;
            divid = $(this).attr('id');
        } 
    });

    alert (divid);
});

        </script>
    </head>
    <body>
        <div id="div1">
            <div>content</div>
            <div>content</div>
            <div>content</div>
        </div>
        <div id="div2">
            <div>content</div>
            <div>content</div>
            <div>content</div>
            <div>content</div>
        </div>
        <div id="div3">
            <div>content</div>
            <div>content</div>
        </div>
    </body>
</html>

答案 2 :(得分:2)

var maxDiv = $('div').get().reduce(function(child1, child2) {
  return $(child1).children().length > $(child2).children().length ? child1 : child2;
});
alert(maxDiv.id);

reduce方法为part of ECMAScript 5,因此现代浏览器支持它(效率更高)。如果reduce原型不存在,您可以将Array添加到该原型中,如该链接中所述。

演示here