开发者

Remove css class containing a particular string

How to select and remove class from an element based on string?

E.g

How to remove class="s2" from element <p class="s2 s4 s5"></p>

I'm looking for way to select class based on number - e.g开发者_StackOverflow社区 's' can be string on any signs. Please note that the order can be different.

Any suggestion much appreciated.


What you're looking for is .removeClass:

$('p.s4.s5').removeClass('s2');

EDIT:

$('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(' ');
});

demo


Try this:

//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]);
    }
}

Here's a working JS Fiddle

EDIT

As someone pointed out in the comments, the above code will only remove the CSS classes from the first p tag (as per your example). The code below will remove all CSS classes ending in two from all p elements.

$('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]);
        }
    }
});


You can pass a function to removeClass() and have it return the classes to remove.

To do that, you can use split(), $.map() and join() to build a new string consisting only of the class names that contain your number:

var yourNumber = 2;
$("p").removeClass(function(index, classes) {
    return $.map(classes.split(" "), function(value) {
        return (value.indexOf(yourNumber.toString()) >= 0 ? value : null);
    }).get().join(" ");
});


$("p").removeClass('s2');

will work for you (in this case)


I dont think you can do this directly.

var class_array = $('#your_html').attr('class').split()

This will return all classes as an array.

One way would be to then check against all the elements of class_array, then call .removeClass() on 'your html' if a condition is satisfied.


What do you think about this solution?

var ClassSelector = '2';

$('p').removeClass('*' + ClassSelector + '*');


@Eric, for your removeClass callback function solution. Works great, as long as you don't use "class" as the second parameter, at least in cases when it will be caught as a reserved word. I just replaced with "c," and it worked fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜