How to remove the specific class, starts with "color" in jquery [duplicate]
Asked Answered
S

2

9

I want remove class, starts with "color". the classes are added dynamically i didn't know many class starts with color.

<div id="sample" class="color1 orange color2 color3 blue"></div>

Jquery

$("#sample").removeClass("[class^='color']");

But it doesn't work. Any Help?

Spectrophotometer answered 5/8, 2014 at 9:19 Comment(0)
C
10

Loop over all the classes and test if they begin with color.

var classes = $("#sample").attr("class").split(' ');
$.each(classes, function(i, c) {
    if (c.indexOf("color") == 0) {
        $("#sample").removeClass(c);
    }
});
Cristophercristy answered 5/8, 2014 at 9:23 Comment(0)
G
7

This will work here

$('div')[0].className = $('div')[0].className.replace(/\bcolor.*?\b/g, '');

OR

 $('div').attr('class',$('div').attr('class').replace(/\bcolor.*?\b/g, ''));

Basically here I am getting each word in classes & replacing anything which starts with color.

Gardal answered 5/8, 2014 at 9:22 Comment(11)
Nice solution, but a bit of an explanation would be nice.Venetian
Maybe not an issue for this poster, but it won't work for class="color-blue" because \b will stop at the -.Cristophercristy
As it's a jQuery question, why not use attr('class')?Niigata
@TrueBlueAussie: Conversely, what's wrong with using className? You skip the overhead of attr(), and available className is available in all browsers.Venetian
@Matt: [0].className is less robust than .attr('class') (from a maintenance perspective) and attr() requires no knowledge of the DOM element properties. Just a suggestion. Feel free to use raw JS all you wish :)Niigata
@TrueBlueAussie added that also, but I don't know what is better.Gardal
$('div').attr('class',$('div').attr('class').replace(/\bcolor.*?\b/g, '')); would do... no need for the function as you are only processing one elementNiigata
In both cases you should it is preferred to only run the selector once (and use a temp variable for the jQuery element) or better yet use the version of attr that takes a function (which will then work on multiple elements - see following) :)Niigata
@Matt: You certainly can't do this with the DOM property: $('div').attr('class', function (i, attr) {return attr.replace(/\bcolor.*?\b/g, ''); }); This will operate independently on each matching element so will handle multiples properly. :)Niigata
@TrueBlueAussie: Array.prototype.forEach.call(document.querySelectorAll('div'), function (el) { el.className = el.className.replace(/\bcolor.*?\b/g, ''); });Venetian
@Matt... OK, you can do it with DOM (if you are willing to over-complicate the code to prove a point) :) RemoveClass actually takes a function as well. So I still say jQuery is cleaner than raw JS (IMHO). :)Niigata

© 2022 - 2024 — McMap. All rights reserved.