2010-09-24 83 views
23

是否有一種吱吱的方法來選擇元素的最深的孩子?在jQuery中選擇最深的孩子

例子:

<div id="SearchHere"> 
    <div> 
    <div> 
     <div></div> 
    </div> 
    </div> 
    <div></div> 
    <div> 
    <div> 
     <div> 
     <div id="selectThis"></div> 
     </div> 
    </div> 
    </div> 
    <div> 
    <div></div> 
    </div> 
</div> 
+0

並不意味着作爲一個批評,但我對你爲什麼會想着迷? – 2010-09-24 14:26:50

+1

對於所有那些通過搜索引擎發現的人來說,我從喬納森的patrick dw的改進版本中更新了主旨。還擴大了一點點的指示。你可以在這裏找到它:[jQuery最深的插件要點](https://gist.github.com/1014671「jQuery最深的插件要點」) – 2011-06-08 15:54:54

回答

27

編輯:這可能是比我原來的答覆更好的方法:

例子:http://jsfiddle.net/patrick_dw/xN6d5/5/

var $target = $('#SearchHere').children(), 
    $next = $target; 

while($next.length) { 
    $target = $next; 
    $next = $next.children(); 
} 

alert($target.attr('id')); 

或這是連短一點:

例子:http://jsfiddle.net/patrick_dw/xN6d5/6/

var $target = $('#SearchHere').children(); 

while($target.length) { 
    $target = $target.children(); 
} 

alert($target.end().attr('id')); // You need .end() to get to the last matched set 

原來的答覆:

這似乎工作:

例子:http://jsfiddle.net/xN6d5/4/

var levels = 0; 
var deepest; 

$('#SearchHere').find('*').each(function() { 
    if(!this.firstChild || this.firstChild.nodeType !== 1 ) { 
     var levelsFromThis = $(this).parentsUntil('#SearchHere').length; 
     if(levelsFromThis > levels) { 
      levels = levelsFromThis; 
      deepest = this; 
     } 
    } 
}); 

alert(deepest.id); 

如果您知道最深處將是某個標記(或其他標記),則可以通過將.find('*')替換爲.find('div')來加速它。

編輯:更新以只檢查長度如果當前元素確實具有firstChild或如果這樣做,該則firstChild不是一個類型1節點。

+1

太棒了!完美的作品!我也將其封裝在一個jQuery插件中。這裏:https://gist.github.com/714851 – Jonathan 2010-11-25 03:28:24

+0

@jonathanconway - 更新我的答案,可能是更有效的版本。 – user113716 2010-11-25 12:23:34

+2

@ user113716我做了一個更短的版本http://jsfiddle.net/xN6d5/44/ :) – EaterOfCode 2013-01-21 15:24:45

3

我不認爲你可以直接做,但你可以嘗試

var s = "#SearchHere"; 
while($(s + " >div ").size() > 0) 
    s += " > div"; 
alert($(s).attr('id')); 
5

這裏有答案略有改善,從@ user113716,這個版本的處理時,有沒有孩子的情況下,返回目標本身。

(function($) { 

    $.fn.deepestChild = function() { 
     if ($(this).children().length==0) 
      return $(this); 

     var $target = $(this).children(), 
     $next = $target; 

     while($next.length) { 
      $target = $next; 
      $next = $next.children(); 
     } 

     return $target; 
    }; 

}(jQuery)); 
+0

+1,因爲我只需要複製/過去以得到我需要的東西,獲得嵌套對象或只是初始對象。謝謝! – Georgio 2016-10-03 18:08:11

1

這個可鏈接的單線程爲我工作,但它假定在下面的層次結構中只有一個葉節點。

jQuery("#searchBeginsHere") 
    .filter(function(i,e){ return jQuery(e).children().size() === 0; }) 
0

每個葉子最深的版本。

http://jsfiddle.net/ncppk0zw/14/

var found = $('#SearchHere *'); 

for (var i = 0; i < found.length; i++) { 
    if (i > 1) { 
     if (found[i].parentNode !== found[i-1]) { 
      // Deepest. Next element is other leaf 
      console.log(found[i-1]); 
      continue; 
     } 
     if (i == found.length-1) { 
      // Deepest. Last element in DOM tree 
      console.log(found[i]); 
     } 
    } 
}