Is there a way in CSS to select the most nested <ul> element that is a child of the parent div.listCan? In this case it is the <ul> that contains list item named Section 1.2.1.1.

The closest I have is to select a <ul> that doesn't have an immediate child <ul>.

This answer to a related question of mine is very clever and there might be a solution in there for here but I haven't figured it out yet.

Thank you.

.listCan { width:fit-content; border: 1px solid black; padding-right: 30px; } div ul:not(:has(li > ul > li > ul)) ul:not(:has(li > ul)) { color:red; } <div class="listCan"> <ul> <li> Section 1 <ul> <li> Section 1.1 <ul> <li> Section 1.1.1 </li> </ul> </li> <li> Section 1.2 <ul> <li> Section 1.2.1 <ul> <li> Section 1.2.1.1 </li> </ul> </li> <li> Section 1.2.2 </li> </ul> </li> </ul> </li> <li> Section 2 <ul> <li> Section 2.1 <ul> <li> Section 2.1.1 </li> </ul> </li> <li> Section 2.2 <ul> <li> Section 2.2.1 </li> <li> Section 2.2.2 </li> </ul> </li> </ul> </li> </ul>

Gary's user avatar

1

If your goal is leaf UL only, your current selector is the correct modern solution:

div ul:not(:has(li > ul)) { color: red; }

If you specifically need the single deepest one, you need JavaScript code

const uls = document.querySelectorAll(".listCan ul"); let deepest = null; let maxDepth = -1; uls.forEach(ul => { let depth = 0; let el = ul; while (el.parentElement) { if (el.parentElement.tagName === 'UL') depth ++; el = el.parentElement; } if (depth > maxDepth) { maxDepth = depth; deepest = ul; } }); deepest.style.color = 'red';

Leaf nodes -> CSS works

Deepest single nodes -> requires JS

Ivan Tereshchenko's user avatar

I would just use div ul:not(:has(ul)) selector meaning

any ul element, that is child of div, that has not any ul elements as children (direct or deeper in the tree).

It will also correctly match node with Section 1.1.1

See example below:

.listCan { width: fit-content; border: 1px solid black; padding-right: 30px; } div ul:not(:has(ul)) { color: red; } <div class="listCan"> <ul> <li> Section 1 <ul> <li> Section 1.1 <ul> <li> Section 1.1.1 </li> </ul> </li> <li> Section 1.2 <ul> <li> Section 1.2.1 <ul> <li> Section 1.2.1.1 </li> </ul> </li> <li> Section 1.2.2 </li> </ul> </li> </ul> </li> <li> Section 2 <ul> <li> Section 2.1 <ul> <li> Section 2.1.1 </li> </ul> </li> <li> Section 2.2 <ul> <li> Section 2.2.1 </li> <li> Section 2.2.2 </li> </ul> </li> </ul> </li> </ul>

Michał Turczyn's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.