ARTICLE AD BOX
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.
3,2742 gold badges19 silver badges51 bronze badges
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
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:
42k18 gold badges58 silver badges91 bronze badges
Explore related questions
See similar questions with these tags.
