删除包含特定字符串的css类

Ila*_*sda 4 javascript jquery

如何根据字符串从元素中选择和删除类?

例如

如何class="s2"从元素中删除<p class="s2 s4 s5"></p>

我正在寻找基于数字选择类的方法 - 例如's'可以在任何符号上串. 请注意,订单可能有所不同.

任何建议都非常感谢.

Eri*_*ric 6

您正在寻找的是.removeClass:

$('p.s4.s5').removeClass('s2');
Run Code Online (Sandbox Code Playgroud)

编辑:

$('p').removeClass(function(i, class) {
    var classes = class.split(' ');  //get an array of all the classes
    var remove = [];                 //classes to remove

    $.each(classes, function() {
        if(this.match(/2$/))   //if the class name ends in 2
            remove.push(this); //add it to the list of classes to remove
    });

    return remove.join(' ');
});
Run Code Online (Sandbox Code Playgroud)

演示


Jam*_*ill 5

试试这个:

//Get an array of css classes
var aryClasses = $('p').attr('class').split(' ');

//Loop over array and check if 2 exists anywhere in the class name
for(var i = 0; i < aryClasses.length; i++)
{
    //Check if 2 exists in the class name
    if(aryClasses[i].indexOf('2') != -1)
    {
        //2 Exists, remove the class
        $('.s2').removeClass(aryClasses[i]);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个有效的JS小提琴

编辑

正如有人在评论中指出的那样,上面的代码只会从第一个p标签中删除CSS类(根据你的例子).下面的代码将从所有p元素中删除所有以两个结尾的CSS类.

$('p').each(function() {
    var aryClasses = $(this).attr('class').split(' ');

    for (var i = 0; i < aryClasses.length; i++) {
        if (aryClasses[i].indexOf('2') != -1) {
            $(this).removeClass(aryClasses[i]);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)