How to remove the class corresponding to the template from the class attribute, but save the rest of the classes?

I want to remove classes that end with a blue character from the class attribute for 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 ending in "blue"

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

How do I put these mapped class names from a class attribute?

+5
source share
2 answers

You can print the full class name using a regular expression, for example:

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

One thing you need to understand is that it $('[class$="blue"]')works with the entire attribute with the name class. I do not use individual class names. Thus, it will match:

class="happy text_blue"

But this will not match:

class="text_blue happy"

class "blue". , "blue", , , :

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

, , JS :

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

, :

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

, , , :

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

, . HTML :

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

.text_blue CSS .text.blue. "" .

+3

All Articles