How to check if any of the li's are selected or not?
<div id='id'>
<ul id='ul'>
<li id='1' class=开发者_JAVA百科"">a</li>
<li id='2' class="">a</li>
<li id='3' class="">a</li>
<li id='4' class="select">a</li>
<li id='5' class="">a</li>
</ul>
</div>
How do I know if any of the <li>
s have a select
class? If found, how do I remove that class?
The following will remove the select
class from all <li>
elements that have it:
$('li.select').each(function() { $(this).removeClass('select'); });
To find if any li is selected use
$('#ul > .select');
and use removeClass to remove select
.removeClass('select');
use
removeClass
$('#ul li').removeClass("select");
to find this class is exist ? use
hasClass
I'd do it like this:
$("#ul > li").filter(function(index) { return $(this).hasClass("select"); }).removeClass("select");
EDIT:
Interesting test case on jsperf showing that indeed, filter is the slowest method, while selector method is the fastest.
精彩评论