最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论
<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.

发布评论

评论列表(0)

  1. 暂无评论