How to select the last item that does not have a specific class?

advertisements

This question already has an answer here:

  • Combining :last-child with :not(.class) selector in CSS 1 answer

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>

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>