Matt Coady
Matt Coady

Reputation: 3856

jquery get the last element at the end of a tree

If I have a structure like this:

<div>
  <div>
    <div>blah</div>
  </div>
</div>


<div>
  <div>
    <div>
      <div>blah</div>
    </div>
  </div>
</div>

Is there jquery to target the deepest elements (where the blahs are located)?

Upvotes: 0

Views: 1214

Answers (3)

patrick
patrick

Reputation: 11731

A bit of recursive jQuery:

$(document).ready(function(){
    alert(deepest($("div:first")).html());

    function deepest(f){
        if(f.find("div").length)return deepest(f.find("div"));
        else return f;
    }
});

Gets the first DIV with no children starting from whatever you pass to Deepest

JSFiddle

Upvotes: 0

j08691
j08691

Reputation: 208032

$('div').each(function () {
    if ($(this).children().length == 0) {
        //do something
    }
})

Upvotes: 1

Jason P
Jason P

Reputation: 27022

This will select anything that doesn't have any child elements:

http://jsfiddle.net/YWARr/

$('div:not(:has(*))')

Upvotes: 4

Related Questions