2012-10-24 42 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

相關問題