Select the last element that does not contain a specific class

advertisements

I have a list of items, and I would like to find the last item in the list, but the item cannot have specific class. How to write code, so that it checks for class name also.

$('ul li:last')
$('ul li:not(.special)')


You can easily use jQuery to select the last item it found in the list. So combine what you have with last() and you are golden:

// Reference: $("ul li:not('.y')").last().text()
document.write('The last non `y` class contains the text: ' + $("ul li:not('.y')").last().text() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<ul>
  <li class="t">Not me.</li>
  <li class="y">Not me.</li>
  <li class="t">Not me.</li>
  <li class="y">Not me.</li>
  <li class="t">Not me.</li>
  <li class="y">Not me.</li>
  <li class="t">This one please!</li>
  <li class="y">Not me.</li>
</ul>

Heres the docs: https://api.jquery.com/last/

Update

You can, of course, just use the CSS selectors nested as well like @RejithRKrishnan said in the comments.

// Reference: $("ul li:not('.y')").last().text()
document.write('The last non `y` class contains the text: ' + $("ul li:not('.y'):last").text() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<ul>
  <li class="t">Not me.</li>
  <li class="y">Not me.</li>
  <li class="t">Not me.</li>
  <li class="y">Not me.</li>
  <li class="t">Not me.</li>
  <li class="y">Not me.</li>
  <li class="t">This one please!</li>
  <li class="y">Not me.</li>
</ul>