Monday, February 13, 2012

How do you remove a class that matches a pattern from the class attribute, but retain the other classes?


I want to delete the classes that end with 'blue' from the class attribute on all tags



sample html




<p class="text_blue happy">this is blue text</p>
<p class="text_red nothappy">this is red text</p>
<img class="img_blue nothappy" />



This will give me all the elements with classes that end with 'blue'




$('[class$=blue]');



how do I pop these matched classnames off of the class attribute?

2 comments:

  1. If you're going to be doing this a lot, you might want to change how you assign classes. You can make your HTML like this:

    <p class="text blue happy">this is blue text</p>


    and then instead of using a selector of .text_blue in your CSS, use .text.blue instead. Then you can simply remove "blue" from the classes.

    ReplyDelete
  2. You can pull the whole class name out with a regular expression like this:

    $('[class$="blue"]').each(function() {
    var clsName = this.className.match(/\w*blue\w*/)[0];
    });


    One thing that you should realize is that $('[class$="blue"]') operates on the entire attribute named class. I does not operate on individual class names. So, it will match:

    class="happy text_blue"


    But, it will not match:

    class="text_blue happy"


    because the class attribute does not end with "blue". If you want it to get any class name that contains "blue" regardless of where it is positioned in the class name attribute, you would have to use:

    $('[class*="blue"]').each(function() {
    var clsName = this.className.match(/\w*blue\w*/)[0];
    });


    If you further wanted to filter out class names that did not end with blue, you could do that with JS like this:

    $('[class*="blue"]').each(function() {
    var match = this.className.match(/\w*blue(\b|$)/);
    if (match) {
    var clsName = match[0];
    }
    });


    If you want to remove these class names from the objects, you could do it like this:

    $('[class*="blue"]').each(function() {
    var match = this.className.match(/\w*blue(\b|$)/);
    if (match) {
    $(this).removeClass(match[0]);
    }
    });


    It could also be done this way which seems a little cleaner, but it doesn't perfectly clean up extra whitespace around the class name it's removing:

    $('[class*="blue"]').each(function() {
    this.className = this.className.replace(/\w*blue(\b|$)/, "");
    });

    ReplyDelete