5

I know that this question was answered multiple times here on stackoverflow, but i just can't get it to work on my problem.

What i want to do is, when a <label> is clicked, check for the labels class and change all matching elements to backgroundColor : #000000

Here is my code:

$(function() {
    $('label').click(function(){
        var group = this.className ;
        $('label .'+group).css({
            'backgroundColor'   : '#000000'
        })  ;
    })  ;
});

Unfortunately, this just does nothing. It even throws no error. Where is my fault?

Solution

I had to remove the whitespace in the selector:

$('label.'+group)
8
  • What is your error? Also, please post the html. Commented Feb 21, 2013 at 17:10
  • What is the value of group? Commented Feb 21, 2013 at 17:11
  • 2
    Maybe you should remove the whitespace in $('label .'+group) Commented Feb 21, 2013 at 17:12
  • 2
    It is possible that the label contains more than one class name, which could cause problems for your selector. We need more information. Commented Feb 21, 2013 at 17:13
  • 3
    @Sprottenwels: The space means "descendant of". api.jquery.com/descendant-selector $('label.a_2') means "labels with the class a_2", $('label .a_2') means "any element with the class a_2 that's a descendant of a label". Commented Feb 21, 2013 at 17:18

1 Answer 1

11

Maybe you should remove the whitespace in $('label .'+group).

$('label .'+group) means all the elements with the group class in all <label>, while $('label.'+group) means the all <label> with group class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.