Question: In jQuery, how would I descend as far as possible into the HTML tree?

For simplicity, I only have one path going downward. 

(related but bonus: how do I find the deepest element with multiple downward paths?)

```
<html>  
  <table id="table0">  
    <tr>  
      <td id="cell0">  
        <div class"simple">  I want to change this information </div>  
      </td>
    </tr>  
  </table>  
</html>

```

I want to change the innermost HTML of the cell named **cell0** but I don't necessarily know the names of all the classes inside. Is it possible to select this far without knowing these names?

Thanks much!

Answer: 
Well, starting from a basis that you have no idea where this "deepest" node is, you could do something like this:

```
$.fn.deepest = function() {
  var depth = 0;
  this.find('*').each(function() {
    var d = $(this).parents().length;
    depth = Math.max(d, depth);
  });
  return this.find('*').filter(function() {
    return this.parents().length === depth;
  });
});

```

Then

```
var $deepest = $('body').deepest();

```

would (excepting the 12 bugs probably in my code) would be a jQuery object for the set of deepest elements.

*edit* — one of my dozen bugs is that this doesn't take into account the depth of the starting node(s) - that'd be a trick to figure out. Might be better to refactor it so that it finds the deepest of the originally-selected list:

```
$.fn.betterDeepest = function() {
  var depth = 0;
  this.each(function() {
    depth = Math.max(depth, $(this).parents().length);
  });
  return this.filter(function() { return $(this).parents().length === depth; });
});

```

and to get the deepest on the page you'd do:

```
var deepest = $('*').betterDeepest();

```
It's not jquery specific, but this recursive solution can be tweaked to do whatever you want.

```
function findDeepest (elem) {
 var result = {maxDepth: 0, deepestElem: null}
 descend(elem, 0, result);
 if (result.maxDepth > 0)
  alert (result.deepestElem.tagName + " " + result.maxDepth);
 }

function descend(elem, depth, result) {    
 switch (elem.nodeType) {
    case 1: // ELEMENT_NODE
        if (depth > result.maxDepth) {
         result.maxDepth = depth;
         result.deepestElem = elem;
         }
        for (var i=0; i<elem.childNodes.length; i++)
           descend(elem.childNodes[i], depth + 1, result);
        break;
    case 3: // TEXT_NODE
    case 4: // CDATA_SECTION_NODE
    case 5: // ENTITY_REFERENCE_NODE
    case 8: // COMMENT_NODE
        // handle these cases as needed
    break;
    }
}

```