As other's have commented, this isn't possible with CSS at this time. The :has
pseudo-class selector might provide for a way down the road.
In the meantime, here are a few options:
$("li:has(a):last").addClass("last");
li {
background: #babaca;
border: 1px solid #E4E4E4;
}
li > a {
background: green;
}
li.last {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
<li> test A </li>
<li> <a> test B</a> </li>
<li> test C </li>
<li> <a> test D</a> I want to select this one!</li>
<li> test E </li>
<li> test F </li>
</ul>
#2 A small plain JavaScript function to find and apply a .last
class to the last li > a
element.
The function findLastA()
accepts a selector to target a ul
element, then finds the last li
containing an a
element, and applies the .last
class to it.
Keep in mind this is made specifically for the HTML structure outlined in the question.
function findLastA(el) {
var listItems = Array.from(document.querySelectorAll(el + " > li"));
for (let i = listItems.length - 1; i >= 0; i--) {
let childNodes = listItems[i].children;
if (childNodes.length && childNodes[0].tagName === "A") {
listItems[i].classList.add("last")
break;
}
}
}
// Call the function
findLastA("#list");
li {
background: #babaca;
border: 1px solid #E4E4E4;
}
li > a {
background: green;
}
li.last {
background: red;
}
<ul id="list">
<li> test A </li>
<li> <a> test B</a> </li>
<li> test C </li>
<li> <a> test D</a> I want to select this one!</li>
<li> test E </li>
<li> test F </li>
</ul>