2012-10-24 106 views
3

我想通过jQuery搜索我的HTML代码以获得带有最多HTML标签的div。在下面的例子中,jQuery应该返回#div2,因为它包含4个div。如何通过jQuery抓取带有大多数标签的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> 

对不起,如果这个例子有点含糊 - 我不认为一个非常具体的代码块是必要的。提前致谢。

+0

你尝试过什么吗? – Sibu

+0

我想不出任何会做到这一点的东西......但也许是因为时间是晚上11点 –

回答

12

您可以通过和keeping 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); 
    } 
}); 
+0

谢谢,我很快就会将它放到我的源代码中,看看它是否正常工作 –

+0

这将工作,如果你喜欢有id,你可以使用attr作为你所需的即 alert($(maxChildDiv).attr(“id”)) – Raghurocks

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
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

相关问题