Delete all classes after a certain class

自闭症网瘾萝莉.ら 提交于 2019-12-05 22:41:08

You can try the following, but your classes might not be in the same order as they appear in the HTML source:

$('#thisdiv').attr('class', function(i, v)
{
    var classes = v.split(' '),
        position = $.inArray('class3', classes);

    return classes.slice(0, position + 1).join(' ');
});

Here's the fiddle: http://jsfiddle.net/FNUK2/


A more succinct way would be to just slice the string itself:

$('#thisdiv').attr('class', function(i, v)
{
    return v.substr(0, v.indexOf('class3') + 6);
});

but I find working with arrays easier.


If you want to use it in the jQuery chain, you'll have to first add it to jQuery's prototype:

$.fn.removeClassesAfter = function(className)
{
    return this.each(function()
    {
        $(this).attr('class', function(i, v)
        {
            var classes = v.split(' '),
                position = $.inArray(className, classes);

            return position == -1 ? v : classes.slice(0, position + 1).join(' ');
        });
    });
};

Here's the fiddle: http://jsfiddle.net/FNUK2/11/

function removeAllClass(selector, after, before) {
    $(selector).attr('class', function(i, oldClass) {
        var arr = oldClass.split(' ');
        if (!before) {
            arr.splice(arr.indexOf(after)+1).join(' ');
            return arr.join(' ');
        } else {
            return arr.slice(arr.indexOf(after), arr.indexOf(before) + 1).join(' ');
        }
    });
}

Use:

  • all after class3

    removeAllClass('#thisdiv', 'class3');

    DEMO

  • from class1 to class3

    removeAllClass('#thisdiv', 'class1', 'class3');

    DEMO

According to comment

UPDATE: I wonder if I can make it work with $('#thisdiv').removeAllClass('class3');

$.fn.removeAllClass = function(after, before) {
    $(this).attr('class', function(i, oldClass) {
        var arr = oldClass.split(' ');
        if (!before) {
            arr.splice(arr.indexOf(after) + 1).join(' ');
            return arr.join(' ');
        } else {
            return arr.slice(arr.indexOf(after), arr.indexOf(before) + 1).join(' ');
        }
    });
}

Use:

  • all after class3

    $('#thisdiv').removeAllClass('class3');

    DEMO

  • from class1 to class3

    $('#thisdiv').removeAllClass('class1', 'class3');

    DEMO

Simple demo http://jsfiddle.net/XaBjX/

Behaviour: anything after class3 will be removed you can see the before and after alert on screen

APIs used: indexOf, prop, removeClass.

Hope this helps,

code

var getClass = $("#thisdiv").prop('class');
alert(" Classes before remove ==> " + getClass);

getClass = getClass.substr(getClass.indexOf('class3')+1);

$("#thisdiv").removeClass(getClass.toString());

alert("Classes After remove ==> "+ $("#thisdiv").prop('class'));​

try this:

var c = $('#thisdiv').prop('class')
$('#thisdiv').prop('class', c.slice(0, c.indexOf('3')+1))

Demo

There's no built-in way of handling "classes" like this. But there should be no shortage of ways to handle chopping up a string, which is all this is.

Grab the string of classes (getClass()), modifying it using whatever string truncating technique seems to meet your requirements, and then set it again with .attr('class', newString).

No. There's no real guarantee that the classes will be in any sort of order.

If they are indexed somehow, you can parse them out... but otherwise this isn't going to work. If you're just attempting to store information, consider using the HTML5-modelled .data() functions.

To do something like this correctly might be a little bit expensive. You need to replace the class attr by iterating over existing classes and removing those that don't fit your criteria. The order of classes from the class attribute are not guaranteed to be in any order, in general:

function removeAbove(prefix, max) {
    var regex = new RegExp('^' + prefix + '(\\d+)$');
    return function (v) {
        var match = regex.exec(v);
        if (!match || parseInt(match[1], 10) <= max) {
          return v;
        }
    }
}

function processClasses(keys, fn) {
    var i = keys.length,
        result = [],
        temp;
    while (i--) {
        temp = fn(keys[i]);
        if (temp) {
            result.push(temp);
        }
    }
    return result.join(' ');
}

$('#thisdiv').attr('class', function (idx, cls) {
    return processClasses(cls.split(' '), removeAbove('class', 3));
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!