views:

64

answers:

2

Hi, is there a cheep method to select the deepest child of an element ?

Example:

<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>
+2  A: 

This would seem to work:

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

If you know that the deepest will be a certain tag (or something else), you could speed it up by replacing .find('*') with .find('div') for example.

EDIT: Updated to only check the length if the current element does not have a firstChild or if it does, that the firstChild is not a type 1 node.

patrick dw
+2  A: 

I don't think you can do it directly but you can try

var s = "#SearchHere";
while($(s + " >div ").size() > 0)
    s += " > div";
alert( $(s).attr('id') );
Loïc Février