Search code examples
jqueryaddclassremoveclass

Select element and add class [selected] to different element while removing the class [selected] from all others


I´ve tried to find the answer on my own but didn´t manage to get any results which could help me solve the problem. The reason for this is probably that I wasn´t able to articulate my question well enough to find the answer or didn´t realize I had the answer in front of me and wasn´t able to understand it.

Since in many of my google searches this site came up I thought after two days of searching I should register and ask the question myself.

I made an quick jsfiddle which basically solves my problem but the code is very repetitive and might be suitable for a couple elements it is going to blow up my site exponentially.

My jsfiddle: http://jsfiddle.net/3Unhe/1/

The answer is probably simple but I have basically zero knowledge of javascript/jquery.

My idea to solve this better would be in plain english: if #id clicked remove class .selected from all .container id´s add class .selected to .container#id

html:
<div class="titel1">titel</div>
<div class="foto1">foto</div>
<div class="name1">name</div>
<br />
<a href="javascript:void(0);" class="titel">
selected titel
</a>
<br />
<a href="javascript:void(0);" class="foto">
selected foto
</a>
<br />
<a href="javascript:void(0);" class="name">
    selected name
</a>

jQuery:
$('.titel').click(function () {
    $('.name1').removeClass('selected');
    $('.foto1').removeClass('selected');
    $('.titel1').addClass('selected');
});

$('.foto').click(function () {
    $('.titel1').removeClass('selected');
    $('.name1').removeClass('selected');
    $('.foto1').addClass('selected');
});

$('.name').click(function () {
    $('.foto1').removeClass('selected');
    $('.titel1').removeClass('selected');
    $('.name1').addClass('selected');
});


css:
.selected {
font-weight:bold;
}

Any help is appreciated. Regardless if you completely solve it or provide a link/ideas to help me solve it on my own. I am not posting here because I am lazy but I wasn´t able to solve it and I have no idea how to better articulate my problem to find the answer on my own.

Even though I used jquery I am perfectly fine using javascript instead.

Thank you very much.

Freubau


Solution

  • Try:

    $('.titel1, .foto1, .name1').on("click",function(){
    
       $("."+$(this).attr("class").substr(0, $(this).attr("class").length-1))
       .addClass("selected")
       .siblings()
       .removeClass("selected");
    
    });
    

    This will look for the elements with the same classname the clicked element has, but without it's last character.

    F.e.: clicking on the element .titel1 will

    • add the "selected" class to .titel, and

    • remove the "selected" class from it's siblings ( .foto and .name )