jqueryselectorwildcardremoveclass

jQuery: Wildcard class selector in removeClass


This code snippet works to remove an existing class, before adding a new one, when I specify it directly (ie, 'ratingBlock', 'ratingBlock1', 'ratingBlock2', etc.). But when I use a wildcard selector in the removeClass ('[class^="ratingBlock"]'), it doesn't work. Am I doing something wrong? Thanks.

<style type="text/css">
.ratingBlock {background:gold !important;}
.ratingBlock1, .ratingBlock2, .ratingBlock3, .ratingBlock4, .ratingBlock5 {background:LightGreen;}
</style>

<div class="test block ratingBlock">
Broken
<div><a href="#" class="ratingLink ratingNo-1">1+</a></div>
<div><a href="#" class="ratingLink ratingNo-2">2+</a></div>
<div><a href="#" class="ratingLink ratingNo-3">3+</a></div>
</div>

<script type="text/javascript">
// <![CDATA[
jQuery(document).ready(function(){
    initRatingWorks();
});

function initRatingWorks() {
    jQuery("a.ratingLink").bind('click', function() {
      var star = jQuery(this);
      var ratingBlock = star.parents('div.test.block');
      var rating = star.attr('class').match(/\d+/);

      if (ratingBlock.attr('class').indexOf('ratingBlock') !== -1) {
          ratingBlock.removeClass('[class^="ratingBlock"]').addClass('ratingBlock' + rating);
      }
      else {
          ratingBlock.addClass('ratingBlock' + rating);
      }

      return false;
    });
}
// ]]>
</script>

Solution

  • $.removeClass() doesn't take a selector as a parameter, only a class name (or class names).

    See: Removing multiple classes (jQuery)

    So you basiacally need to call:

    $.removeClass('ratingBlock1 ratingBlock2 ratingBlock3 ratingBlock4 ratingBlock5');