Question: How do I find the last descendent of a div?

Question

How do I find the last descendent of a div?

Answers 2
Added at 2017-01-01 11:01
Tags
Question

I want to find last descendent div of the html below. I tried but it finds the first occurrence of the div.

How can I achieve this?

HTML:

<div class='greatparent'>
  <div>
    <div>
      <div>
        <div>
          <div>
            find this div element
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

jQuery:

$('.greatparent').find('div:last-child').html('you found me');
Answers
nr: #1 dodano: 2017-01-01 11:01

You can solve this using jQuery by finding the only <div> element that doesn't have a <div> child:

$(".greatparent").find("div:not(:has(div))")
nr: #2 dodano: 2017-01-01 11:01

You can use jQuery :last selector

var last = $(".greatparent div:last");
console.log(last.children().length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class='greatparent'>
  <div>
    <div>
      <div>
        <div>
          <div>
            find this div element
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Source Show
◀ Wstecz