Reputation: 1285
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)')
Upvotes: 2
Views: 85
Reputation: 17340
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/
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>
Upvotes: 1
Reputation: 95
this might help. At the ele will contain the last element without that class.
var ele;
$('ul li').each(function(){
if(!$(this).hasClass("yourclass"))
{
ele = this;
}
});
Upvotes: 0