Reputation: 89
I want to addClass()/removeClass() for divs with different class name and I try to find them by id
.
How I can make this work?
JS:
$(document).ready(function() {
$("#button_hof").click(function() {
$("#button_hof").removeClass("selected");
$(this).addClass("selected");
return false;
});
});
HTML:
<div id="button_hof" class="button_hof selected"></div>
<div id="button_hof" class="button_hof"></div>
<div id="button_hof" class="button_hof2"></div>
<div id="button_hof" class="button_hof2"></div>
Upvotes: 1
Views: 2736
Reputation: 206
You do not need to have id's on each of the items you are watching. As the other commenter stated, the ID
on an element must be unique.
.selected {
color: hotpink;
}
<div class="button_hof selected">1</div>
<div class="button_hof">2</div>
<div class="button_hof">3</div>
<div class="button_hof">4</div>
var allButtons = jQuery('.button_hof');
jQuery('.button_hof').click(function(e){
var $active = jQuery(this);
allButtons.removeClass('selected');
$active.addClass('selected');
});
Upvotes: 4