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 badges4 Answers
Reset to default 13Exclude 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?