How do I select the innermost element?

For single path just find the element that doesn't have child nodes:

$('body *:not(:has("*"))');

Or, in your more specific case $('#cell0 *:not(:has("*"))');

For multiple paths - what if there are multiple equally nested nodes? This solution will give you an array of all nodes with highest number of ancestors.

var all = $('body *:not(:has("*"))'), maxDepth=0, deepest = []; 
all.each( function(){ 
    var depth = $(this).parents().length||0; 
    if(depth>maxDepth){ 
        deepest = [this]; 
        maxDepth = depth; 
    }
    else if(depth==maxDepth){
        deepest.push(this); 
    }
});

Again, in your situation you probably want to get to table cells' deepest elements, so you're back to a one-liner:

$('#table0 td *:not(:has("*"))');

- this will return a jQuery object containing all the innermost child nodes of every cell in your table.


I'd do this through a single recursive function:

// Returns object containing depth and element
// like this: {depth: 2, element: [object]}
function findDeepestChild(parent) {

    var result = {depth: 0, element: parent};

    parent.children().each(
        function(idx) {
            var child = $(this);
            var childResult = findDeepestChild(child);
            if (childResult.depth + 1 > result.depth) {
                result = {
                    depth: 1 + childResult.depth, 
                    element: childResult.element};
            }
        }
    );

    return result;
}