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

javascript - How can I make jQuery's $.each() function skip certain objects based on criteria? - Stack Overflow

programmeradmin0浏览0评论

Say I have the following HTML:

<p class="link"><a href="#">This is a link.</a></p>
<p class="link"><a href="#">This is another link.</a></p>
<p class="link current"><a href="#">This is yet another link.</a></p>
<p class="link"><a href="#">This is still another link.</a></p>

I want to use jQuery's $.each() function to go through all the objects with the class link, but I want to skip the one which also has a class current. How do I do that?

I could check for the existence of the class within the each loop like this:

$('.link').each(function() {
    if (!$(this).hasClass('current'))
        $(this).fadeOut();
})

... but is there a way to specify "class x, but not class y" in jQuery, removing the need for the if condition?

Say I have the following HTML:

<p class="link"><a href="#">This is a link.</a></p>
<p class="link"><a href="#">This is another link.</a></p>
<p class="link current"><a href="#">This is yet another link.</a></p>
<p class="link"><a href="#">This is still another link.</a></p>

I want to use jQuery's $.each() function to go through all the objects with the class link, but I want to skip the one which also has a class current. How do I do that?

I could check for the existence of the class within the each loop like this:

$('.link').each(function() {
    if (!$(this).hasClass('current'))
        $(this).fadeOut();
})

... but is there a way to specify "class x, but not class y" in jQuery, removing the need for the if condition?

Share Improve this question asked Oct 25, 2011 at 12:31 aalaapaalaap 4,4115 gold badges56 silver badges62 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 13

Exclude the elements using the :not() selector:

$('.link:not(.current)').fadeOut();

You can filter your initial jQuery object:

$('.link').filter(function() {
    return !$(this).hasClass('current');
}).fadeOut();
$('.link').each(function() {
    if ($(this).attr('class')!="link current")
        $(this).fadeOut();
})

As Guffa suggested, you can use :not() CSS pseudo-selector. To use it for .each() function, you can do the following (see this jsfiddle as a proof):

jQuery(".link:not(.current)").each(function(index, element){
    jQuery(element).fadeOut();
});

Does it suit your needs?

发布评论

评论列表(0)

  1. 暂无评论