CSS or jQuery solution to select “last in hierarchy” elements?

i have a bunch of nested HTML elements, like

<div>
  <div>
    <div>A</div>
  </div>
  <div>
    <div><span>B</span></div>
  </div>
</div>

Is there a way to only select the innermost divs, those that do not contain any other divs? Notice that div B does have descendants, but no other divs.

Clarification i mean to select all those divs that do not contain another div, but maybe some other tags.


solution

Is there a way to only select the innermost divs, those that do not contain any other divs?

You could combine the :not()/ :has() selectors in order to select the innermost div elements that don’t contain other div elements:

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

Given the HTML you provided, if you don’t want the div with the “A” text node to be selected, you could only select elements that contain other elements, in this case a span:

Example Here

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