Getting the deepest element in jQuery

function deepest(e) {
  var $t = $(e).children();
    
  while($t.length) {
    $t =  $t.children();
  }
    
  return $t.end();
}

I had to deal with editing a title from a landing page as you completed a form. Since the page would create a metric ton of wrappers and it would vary every time, it was getting hard to get the right element to edit while not breaking how styling was working within that landing page's editor.

I made this little function that just returns the deepest element from a selector you send.

Lets say you have the following html structure and there can be an unlimited number of wrappers between the first div and the deepest span.

<div id="foo">
  <span>
    <div>
      <span>text</span>
    </div>
  </span>
</div>

<script>
  console.log( deepest( '#foo' ) );
</script>

This would display the element <span>text</span> in your console.

You could then do things like deepest( '#foo' ).html( 'hello' ); if you wanted to change that text to 'hello' since it returns the element.

Author image
About Solid
Canada Website
I like video games and code.