Fellow Stranger
Fellow Stranger

Reputation: 34013

Toggle styling for active element in group of elements

Given a group of elements with no target attribute (e.g. following code), what is the most effiecient way to set a highlight-styling for a selected element while unsetting the same styling for a previously selected element ?

<div id="uno" class="element_parent">
    <a href="#" class="element">ONE</div>
</div>
<div id="dos" class="element_parent">
    <a href="#" class="element">ONE</div>
</div>
<div id="tres" class="element_parent">
    <a href="#" class="element">ONE</div>
</div>

Upvotes: 0

Views: 93

Answers (3)

adeneo
adeneo

Reputation: 318182

I would add and remove a class on clicking the anchor, like so:

$('.element').on('click', function(e) {
    e.preventDefault();
    $(this).addClass('active')
           .closest('div')
           .siblings('div')
           .find('a')
           .removeClass('active')
});

CSS

.active {color: red;} /* or whatever */

or:

$('.element').on('click', function(e) {
    e.preventDefault();
    $('.element.active').removeClass('active');
    $(this).addClass('active');
});

Upvotes: 4

mr.freeze
mr.freeze

Reputation: 14062

$('.element').on('click',function(e){
    $(this).addClass('active');
    $('.element').not($(this)).removeClass('active');
});

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Something like:

$(".element").click(function() {
    $(".element").removeClass("active");
    $(this).addClass("active");
});

Upvotes: 1

Related Questions