removing a class that contains a set of characters
Asked Answered
W

6

7

Is there a way to remove a class that starts or contains a defined text string?

I have several classes for background color overides that start .bg

.bgwhite
.bgblue
.bgyellow

I've set up a little jquery for a select box that adds and removes modifying classes to an element, in this case an <a href id="buttontostyle"> tag I need to remove these classes that start with .bg, while keeping another class which determines the size of the buttons so something like this:

    $("#buttoncolors").change(function() // buttoncolors is the select id
    {
        var valcolor = $("#buttoncolors").val();
        $("#buttontostyle").removeClass("bg" + "*");
        $("#buttontostyle").addClass(valcolor);

    });
Wame answered 16/4, 2013 at 13:6 Comment(3)
use reg exp to determine the class name starting with pattern and remove it using remove() from jqueryUntangle
duplicate of #58312Rebhun
https://mcmap.net/q/87387/-remove-all-classes-that-begin-with-a-certain-stringUnwept
H
7

You can pass a function to removeClass which returns a list of classes that you want to remove. In this function, you can test to see if each of the classnames begins with bg, then if it does, add it to a list of classes that you want to remove.

$("#buttoncolors").on("change", function () {
  var valcolor = $("#buttoncolors").val();

  $("#buttonstyle").removeClass(function (index, classNames) {
    var current_classes = classNames.split(" "), // change the list into an array
        classes_to_remove = []; // array of classes which are to be removed

    $.each(current_classes, function (index, class_name) {
      // if the classname begins with bg add it to the classes_to_remove array
      if (/bg.*/.test(class_name)) {
        classes_to_remove.push(class_name);
      }
    });
    // turn the array back into a string
    return classes_to_remove.join(" ");
  });

  $("#buttonstyle").addClass(valcolor);
});

Demo: http://codepen.io/iblamefish/pen/EhCaH


BONUS

You can neaten up the code by using a named rather than anonymous function for the callback so that you can use it more than once.

// name the function 
function removeColorClasses (index, classNames) {
  var current_classes = classNames.split(" "), // change the list into an array
      classes_to_remove = []; // array of classes which are to be removed

  $.each(current_classes, function (index, class_name) {
    // if the classname begins with bg add it to the classes_to_remove array
    if (/bg.*/.test(class_name)) {
      classes_to_remove.push(class_name);
    }
  });
  // turn the array back into a string
  return classes_to_remove.join(" ");
}

You can then use this function over and over again by passing in its name where you'd usually write function () { ... }

// code that the dropdown box uses
$("#buttoncolors").on("change", function () {
  var valcolor = $("#buttoncolors").val();

  $("#buttonstyle").removeClass(removeColorClasses);

  $("#buttonstyle").addClass(valcolor);
});

// another example: add a new button to remove all classes using the same function
$("#buttonclear").on("click", function () {
  $("#buttonstyle").removeClass(removeColorClasses);
});
Highfalutin answered 16/4, 2013 at 15:12 Comment(0)
W
3

This should do the trick while still keeping the other classes:

var matches = $('#buttontostyle').attr('class').match(/\bbg\S+/g);
$.each(matches, function(){
    var className = this;
    $('#buttontostyle').removeClass(className.toString());
});
Wavawave answered 16/4, 2013 at 14:19 Comment(0)
J
0

Try this -

$('#buttontostyle:not([class^="bg"])');
Jasperjaspers answered 16/4, 2013 at 13:15 Comment(1)
It wasn't me - but I'm guessing it's because you've answered how two select things without a certain class, the question is how to remove a set of classes beginning with a certain string.Highfalutin
M
0

How about this...

// remove class regex expression function
$.fn.removeClassRegEx = function(regex) {
  var classes = $(this).attr('class');
  if (!classes || !regex) return false;
  var classArray = [];
  classes = classes.split(' ');
  for (var i = 0, len = classes.length; i < len; i++)
    if (!classes[i].match(regex)) classArray.push(classes[i]);
  $(this).attr('class', classArray.join(' '));
};

// run function on #card element
$('#card').removeClassRegEx('brand-');
.card-logo {
  background: black;
  color: white;
}

.brand-mastercard {
  background: red;
}
<code id="card" class="card-logo brand-mastercard">Inspect this element</code>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Source taken from here... https://websanova.com/blog/jquery/jquery-remove-class-by-regular-expression

Marceline answered 10/9, 2018 at 13:19 Comment(0)
O
0

Allows for more flexibility where the user just needs to return true for each class they want to remove:

$.fn.removeClassBy = function (fun) {
  if (!fun) return
  $(this).removeClass(function (index, classNames) {
    const currentClasses = classNames.split(' '); // change the list into an array
    let classesToRemove = []; // array of classes which are to be removed

    $.each(currentClasses, function (index, className) {
      // if the classname begins with bg add it to the classes_to_remove array
      if (fun(className)) {
        classesToRemove.push(className);
      }
    });
    // turn the array back into a string
    return classesToRemove.join(' ');
  })
}

Usage:

$('[class*="some-partial-class-name"]').removeClassBy(className => className.includes('some-partial-class-name'));
Oahu answered 14/6, 2020 at 7:9 Comment(0)
A
-2

Try this

 $("#buttontostyle").removeClass('[class^="bg"]');
Amorette answered 16/4, 2013 at 14:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.