user893970
user893970

Reputation: 899

Easier way to change only one element of a certain class

I wanted to change the style properties of selected element of a certain class. I have five h6 elements and if the user clicks one of them, the style of the selected one changes and others turns default style. For example,

$(".change").bind("click",function (){ 
     $(".change").css("color","white");
      $(this).css("color","red");
    });

These codes change the color of all members of the class and lastly change the color of the selected one. What i want is like that, changing only the selected one. But, this is not a good way because changing the other properties of style attribute requires the knowledge about the default ones. For instance, I had to find that my back-ground color was #D4D4D4.Is there any easy way to change only selected element of a class, just like "hover" of css?

Upvotes: 0

Views: 2604

Answers (3)

jfriend00
jfriend00

Reputation: 707556

I'm not 100% sure I know what you're asking, but if the problem you're trying to solve is that you don't want to have to code the CSS state into your javascript, then you should add/remove classes to your objects and let all the style be in your CSS (where it belongs):

$(".change").click(function (){ 
    $(".change").removeClass("selected");
    $(this).addClass("selected");
});

Then just create a CSS rule for the selected class and all other items will have the normal default style.

.selected {color: red;}

Upvotes: 4

Šime Vidas
Šime Vidas

Reputation: 185933

Consider this:

CSS:

h6.selected { color:white; }

JavaScript:

var h6arr = $( 'h6' ).get();

$( h6arr ).click(function () {
    $( h6arr ).removeClass( 'selected' );
    $( this ).addClass( 'selected' );
});

Upvotes: 2

Ben
Ben

Reputation: 13635

instead of using css inside the html element you could toggle or add/remove a css class from your h6 elements.

Upvotes: 0

Related Questions