简体   繁体   中英

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>

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

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

Try this?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM