dylanstewart
dylanstewart

Reputation: 5

How to remove a class with jQuery from all divs not just siblings?

I'm using jQuery to add a class "selected" to a div when a user clicks on it (it adds a red border to a thumbnail). At the same time I want to remove the class from a previously selected div.

I can get this to work if all the divs are siblings, but other divs in the document remain selected. The page I'm designing and developing requires that the divs can't all be siblings. How can I remove the class "selected" on a previously selected div anywhere in the document, not just the siblings?

You can view and edit my example on jsfiddle: http://jsfiddle.net/3s4dM/6/

jQuery:

$(".thumbnail").click(function() {
    $(this).addClass("selected").siblings().removeClass("selected");
})

CSS:

.thumbnail {
    background: #dddddd;
    width: 42px;
    height: 42px;
    margin-bottom: 5px;
}

.thumbnail:hover {
    cursor: pointer;
}

.thumbnail.selected {
    width: 36px;
    height: 36px;
    border: 3px solid #C72D30;
}

HTML:

<section>

    <div class="thumbnail"></div>

</section>

<section>

    <div class="thumbnail"></div>

</section>

<section>

    <div class="thumbnail"></div>
    <div class="thumbnail"></div>
    <div class="thumbnail"></div>

</section>

Upvotes: 0

Views: 851

Answers (4)

francisco.preller
francisco.preller

Reputation: 6629

Try this?

$(".thumbnail").click(function() {
    $('.selected').removeClass('selected');
    $(this).addClass("selected");
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You can use a combined selector to get all div elements with the classes thumbnail and selected then remove the selected class from it.(Since you are again adding selected to current thumbnail ignore that also using not())

$(".thumbnail").click(function() {
    $('.thumbnail.selected').not(this).removeClass("selected")
    $(this).addClass("selected");
})

Demo: Fiddle

Upvotes: 3

CRABOLO
CRABOLO

Reputation: 8793

If there all div's you can do it like this.

$(".thumbnail").click(function() {
    $('div').removeClass('selected');
    $(this).addClass("selected");
});

Upvotes: 0

Felix
Felix

Reputation: 38102

You can remove class selected from all current elements that has .selected and add class selected to clicked .thumnail element:

$(".thumbnail").click(function () {
    $('.selected').removeClass("selected");
    $(this).addClass("selected");
});

Updated Fiddle

Upvotes: 1

Related Questions