How can I select last li
that doesn't have the .hidden
class?
I have HTML and CSS like this:
ul li:last-child:not(:first-child):not(.hidden) button {
background-color: red;
}
<ul>
<li>
<button>1</button>
</li>
<li>
<button>2</button>
</li>
<li class="hidden">
<button>3</button>
</li>
</ul>
To select the last element of a specific class, you can use the CSS :last-of-type pseudo-class. In this snippet, we'll show examples with the HTML <article> and <p> elements.
The :last selector selects the last element. Note: This selector can only select one single element. Use the :last-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the last element in a group (like in the example above).
class is not possible with last-of-type . Edit: To actually add something constructive to this answer, you could fallback to JavaScript to locate this selector, or revise your markup/CSS.
At the current moment, there is no CSS way of being able to find an element that is then followed by another specific element.
Possibly soon, there will be the CSS Relational Pseudo-class :has()
which will make what you want possible. This is currently in the CSS Selectors Level 4 Draft and looks unlikely to be rolled out across any browsers any time soon.
A demo is below but don't expect it to work until the Selectors 4 Draft is at least in Working Draft.
Keep an eye on CanIUse to see when it becomes readily available.
ul li:has(+ .hidden:last-child),
ul li:last-child:not(.hidden) {
background: red;
}
<ul>
<li>
<button>1</button>
</li>
<li>
<button>2</button>
</li>
<li class="hidden">
<button>3</button>
</li>
</ul>
:has()
is available in jQuery though, so here's a jQuery alternative
Read more here from the Official jQuery Docs
$('ul li:has(+ .hidden:last-child), ul li:not(.hidden):last-child').css('background', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<button>1</button>
</li>
<li>
<button>2</button>
</li>
<li class="hidden">
<button>3</button>
</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With