Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select last element that don't have specific class? [duplicate]

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>
like image 951
jcubic Avatar asked Aug 12 '16 12:08

jcubic


People also ask

How do you select the last element with the same class?

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.

How do you choose the last element?

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).

Does last-of-type work with classes?

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.


1 Answers

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>
like image 108
Stewartside Avatar answered Dec 17 '22 20:12

Stewartside