Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 937
albert Jegani Avatar asked Aug 05 '14 09:08

albert Jegani


People also ask

Can you remove a class with jQuery?

jQuery removeClass() MethodThe removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.

How can I replace one class with another in jQuery?

To replace all existing classes with another class, we can use . attr( "class", "newClass" ) instead. As of jQuery 1.4, the . removeClass() method allows us to indicate the class to be removed by passing in a function.

What is the jQuery script to remove a class in an element?

jQuery removeClass() Method The removeClass() method can remove a single class, multiple classes, or all classes at once from the selected elements.

How do you remove an active class?

removeClass() Method. This method removes one or more class names from the selected elements. If no parameter is specified in the removeClass() method, it will remove all class names from the selected elements.


2 Answers

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);
    }
});
like image 145
Barmar Avatar answered Oct 06 '22 06:10

Barmar


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.

like image 35
Mritunjay Avatar answered Oct 06 '22 07:10

Mritunjay