Henry
Henry

Reputation: 277

switching div class between divs (jquery, javascript)

I think this should be a pretty common jquery function but I just couldn't find anything about it.

say I have 10 divs and each div trigger an event when clicked. So when I cilck a div, jquery adds a class, say "clicked" to the div. But how can I set it so when I click another div, it removes the previous div class "clicked" and gives it to the div that I just clicked?

Thanks!!!

Upvotes: 2

Views: 232

Answers (2)

karim79
karim79

Reputation: 342665

$("div.groupname").click(function() {
    $(this).addClass("clicked").siblings().removeClass("clicked");
});

or:

$("div.groupname").click(function() {
    $(this).siblings().removeClass("clicked").end().addClass("clicked");
});

You can try it here.

Upvotes: 8

Jason Gennaro
Jason Gennaro

Reputation: 34855

Try this

$('.one').click(function(){
    $(this).addClass('two');
    $(this).siblings().removeClass('two');
});

css

.one{
    background:red;
    height:50px;
    width:200px;
    margin-bottom:20px;
}

.two{
    background:green;
}

html

<div class="one">
</div>

<div class="one">
</div>

Example: http://jsfiddle.net/jasongennaro/fNWxf/

Upvotes: 1

Related Questions