CodeMoose
CodeMoose

Reputation: 3025

JQuery - remove selected class when using "Attribute starts with" selector?

Working with auto-generated html code, with variable classnames: table-col-44, table-col-19, table-col-121 etc.

I've got a loop that's going through and selecting these variable classes using this jQuery selector functionality:

for(r in replace){
    var targ = replace[r];
    $("[class^='"+targ+"']").each(function(){
        ...
    })
}

The problem is, once I've selected the classes I want to scrub, I can't find a way to target them to remove them. Often these are <p> and <td> tags that have other classes that need to be preserved, so I can't just wipe the class attribute altogether. Is there a way to pass the matched class as an argument to the each() function? Or perhaps there's some kind of $(this).removeClass([selected]) keyword that comes with jQuery? Totally stumped here. Thanks for the help!

Upvotes: 0

Views: 1095

Answers (2)

ramblex
ramblex

Reputation: 3057

Not sure if there's a more jQuery way of doing this but you could try this inside the each:

var newClassName = $(this).attr('class').split(' ').slice(1).join(' ')
$(this).attr('class', newClassName)

This will remove the first class name since you've matched with ^=.

Update:

See here for an example of removing a class by passing a function to removeClass: http://jsfiddle.net/DHxNG/1/. The JS is:

targ = 'table-col';
$('[class*="'+targ+'"]').removeClass(function(index, css) {
    var re = new RegExp(targ+"-\\d+");
    return (css.match(re) || []).join(' ');
});

This is based on code from here: JQuery removeClass wildcard

Upvotes: 2

clav
clav

Reputation: 4251

You can add a startsWith function to the string object's prototype, doing something like this:

if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str){
        return this.indexOf(str) == 0;
    };
}

Then your loop to remove the classes that start with whatever was matched on looks like this:

for(r in replace) {
    var targ = replace[r];
    $("[class^='"+targ+"']").each(function() {
        var $element = $(this);
        var classes = $(this).attr('class').split(' ');
        for(var i = 0; i < classes.length; i++) {
            var cssClass = classes[i];
            if(cssClass.startsWith(targ)) {
                $element.removeClass(cssClass);
            }
        }
    });
}

Upvotes: 0

Related Questions