Add/remove class to label tags I came up with this jQuery snippet to add/remove a class on &lt;label&gt; tags that contain either checkboxes or radio buttons, in order to improve usability so users can see what item(s) they have selected.

But I would like to know if there's a way to optimize the code (or not if that's the case).

$('label input[type=radio], label input[type=checkbox]').click(function() {
  $('label:has(input:checked)').addClass('active');
  $('label:has(input:not(:checked))').removeClass('active');
});
You're adding a click handler to all your inputs, and then implementing the click handler such that each click processes all the labels.  This is probably not what you want.  

I'd suggest the following:

$('label input[type=checkbox]').click(function() {
    $(this.parentNode).toggleClass('active', this.checked);
});

$('label input[type=radio]').click(function() {
    $('input[name="' + this.name + '"]').each(function(){
        $(this.parentNode).toggleClass('active', this.checked);
    });
});


Happily enough, that approach is also more efficient, as it's processing 1 element per click for checkboxes instead of n elements per click.  For radio buttons it still has to process multiple elements, but the number processed is still less than the total number of elements on the page (assuming the page contains more than a single group of radio buttons).  

Here's a live example:  http://jsfiddle.net/DfU3R/3/

As nickles80 rightly notes, however, the performance difference between the two approaches will likely be negligible, and premature optimization is the root of all evil.