2010-09-24 17 views
23

¿Hay un método de cheep para seleccionar el hijo más profundo de un elemento?seleccionar hijo más profundo en jQuery

Ejemplo:

<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

no pretende ser una crítica, pero estoy fascinado por qué te gustaría? –

+1

Para todos aquellos que están encontrando esto a través de los motores de búsqueda, actualicé la esencia de jonathan con la versión mejorada de patrick dw. También expandió las instrucciones un poco. Puede encontrarlo aquí: [jQuery gps de plugin más profundo] (https://gist.github.com/1014671 "jQuery deep plugin gist") –

Respuesta

27

EDIT: Esto es probablemente un enfoque mejor que mi respuesta original:

Ejemplo: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')); 

o el presente, que es incluso una poco más corto:

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

Respuesta original:

Esto parece funcionar:

Ejemplo: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); 

Si sabe que lo más profundo será una determinada etiqueta (u otra cosa), podría acelerarla reemplazando .find('*') con .find('div') por ejemplo.

EDIT: actualizado a la verificación Sólo la longitud si el elemento actual no no tienen una firstChild o si lo hace, que el firstChild no es un nodo de tipo 1.

+1

¡Impresionante! ¡Funciona perfectamente! También he encapsulado esto en un plugin jQuery. Aquí: https://gist.github.com/714851 – Jonathan

+0

@jonathanconway - Actualicé mi respuesta con una versión más eficiente. – user113716

+2

@ user113716 Hice incluso una versión más corta http://jsfiddle.net/xN6d5/44/ :) – EaterOfCode

3

no creo que pueda hacerlo directamente, pero se puede tratar

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

Aquí hay una ligera mejora en la respuesta de @ user113716, esta versión maneja el caso cuando no hay niños y devuelve el objetivo sí mismo.

(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, porque solo tuve que copiar/pasar para obtener exactamente lo que necesito, obtener un objeto anidado o solo un objeto inicial. ¡Gracias! – Georgio

1

Este encadenamiento único funcionó para mí, pero se supone que hay un solo nodo hoja en la jerarquía a continuación.

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

Versión para obtener más profundo para cada hoja.

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]); 
     } 
    } 
}