radbyx
radbyx

Reputation: 9660

Concatenate CSS selectors

Is there a smarter way where I can use $self instead of using foo in $('.foo.bar')... ? It feels like the extra foo is redundent. I don't want to look through some selector I already found.

$('.foo').on('click', function () {
    $self = $(this);
    $('.foo.bar').removeClass('bar'); // Works but feels wrong.
    //$self('bar').removeClass('bar'); // Use something that doesn't uses 'foo' again..
});

EDIT:

Markup code:

<div class="foo bar">
</div>

Notice $('.foo.bar') doesn't have a whitespace between foo and bar.

Upvotes: 2

Views: 1308

Answers (5)

Matt
Matt

Reputation: 75317

All of the current answers assume that the .foo clicked on will be the only .foo with the class bar.

... if that is always the case, then great, but note that these answers aren't direct substitutions for what you've got (since you look for all .foo's with the class bar). The following would be a more direct substitution:

var foos = $('.foo').on('click', function () {
    $self = $(this);

    foos.filter('.bar').removeClass('bar');
});

... but note that this code still isn't a direct substitution, since your code will get the .foo's in the DOM at the time the click event was fired, whereas the alternative I propose will get the .foo's at the time the click event was bound.


Also, checking whether a jQuery element has a class, before removing that class, is kind of redundant; as jQuery won't barf if you tell it to remove a non-existant class from an element; it just won't do anything.

if (self.hasClass('bar')) {
    self.removeClass('bar');
}

... instead, just do this:

self.removeClass('bar');

Upvotes: 1

Kamesh Jungi
Kamesh Jungi

Reputation: 6251

If you are using id for each parent element, you can use something like :

$('.foo').on('click', function () {
   $('#'+this.id).removeClass('bar'); // it will remove child class bar
)};

Upvotes: 0

Rahul Desai
Rahul Desai

Reputation: 15501

Use this simple logic: If X has a class Y, remove class Y from X.

Here is the code:

$('.foo').on('click', function () {

    $self = $(this);

    if($self.hasClass('bar'))
        $self.removeClass('bar');

});

Readup:

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

You could use is or hasClass to check to see if the current element also has the bar class:

$('.foo').on('click', function () {
    $self = $(this);
    $self.is('.bar') && $self.removeClass('bar');
});

Upvotes: 0

void
void

Reputation: 36703

Method 1 hasClass()

$self.hasClass("bar") && $self.removeClass('bar');

Method 2 is()

$seld.is(".bar")  && $self.removeClass('bar');

Method 3 filter()

$seld.filter(".bar").removeClass('bar');

Upvotes: 0

Related Questions