Sylar Sylar - 12 days ago 7
CSS Question

Highlight Selected Div

I have two or more divs with the first being selected. When I click the other div, that div becomes selected. I'm doing this with a background color.

CSS:

.red {background: red}


HTML:

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


JavaScript:

$('.foo').click(function(){
//$(this).toggleClass('red') Not ideal as the active div must always be red
// If selected, remove all red classes then add class?
});


Since it's an event click, I'm not sure how to remove all other classes with red and add red class to the clicked div.

In short, "highlight"
div
when selected and if page is refreshed, the first
div
should have a background of red as that's the selected
div
.

Answer

Using siblings() method get sibling elements and remove red class from them.

$('.foo').click(function() {
  $(this).addClass('red') // add class to clicked element
    .siblings() // get siblings
    .removeClass('red'); // remove class from sibling elements 
});

$('.foo').click(function() {
  $(this).toggleClass('red')
    .siblings().removeClass('red')
});
.red {
  background: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">...</div>
<div class="foo">...</div>
<div class="foo">...</div>

Comments