javascript - How to check if any of the li's are selected or not? - Stack Overflow

<div id='id'><ul id='ul'><li id='1' class="">

<div id='id'>
 <ul id='ul'>
  <li id='1' class="">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?

<div id='id'>
 <ul id='ul'>
  <li id='1' class="">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?

Share Improve this question edited Apr 5, 2011 at 5:22 David Tang 93.7k32 gold badges168 silver badges149 bronze badges asked Apr 5, 2011 at 5:16 jaquilinejaquiline 112 silver badges4 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745076015a4609839.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信