Eliminar todas las clases que comienzan con una cadena determinada


Tengo un div con id="a" que puede tener cualquier número de clases adjuntas, de varios grupos. Cada grupo tiene un prefijo específico. En el javascript, no se que clase del grupo esta en el div. Quiero poder borrar todas las clases con un prefijo dado y luego agregar uno nuevo. Si quiero quitar todas las clases que comienzan con "bg", ¿cómo lo hago? Algo como esto, pero que en realidad funciona:

$("#a").removeClass("bg*");
Author: bluish, 2008-09-12

14 answers

Con jQuery, el elemento DOM real está en el índice cero, esto debería funcionar

$('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, '');
 56
Author: Pat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-28 09:37:03

Una división regex en el límite de palabras \b no es la mejor solución para esto:

var prefix = "prefix";
var classes = el.className.split(" ").filter(function(c) {
    return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = classes.join(" ").trim();

O como un mixin de jQuery:

$.fn.removeClassPrefix = function(prefix) {
    this.each(function(i, el) {
        var classes = el.className.split(" ").filter(function(c) {
            return c.lastIndexOf(prefix, 0) !== 0;
        });
        el.className = $.trim(classes.join(" "));
    });
    return this;
};
 101
Author: sarink,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-15 09:48:39

He escrito un simple jQuery plugin - alterClass, que hace la eliminación de la clase comodín. Opcionalmente añadirá clases también.

$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' ) 
 29
Author: Pete B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-08 17:27:26

No necesita ningún código específico de jQuery para manejar esto. Simplemente use una expresión regular para reemplazarlos:

$("#a").className = $("#a").className.replace(/\bbg.*?\b/g, '');

Puede modificar esto para soportar cualquier prefijo, pero el método más rápido está arriba, ya que la expresión regular se compilará solo una vez:

function removeClassByPrefix(el, prefix) {
    var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g');
    el.className = el.className.replace(regx, '');
    return el;
}
 11
Author: Prestaul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-11 22:46:55

Usando 2ª firma de $.fn.removeClass:

// Considering:
var $el = $('<div class="  foo-1 a b foo-2 c foo"/>');

function makeRemoveClassHandler(regex) {
  return function (index, classes) {
    return classes.split(/\s+/).filter(function (el) {return regex.test(el);}).join(' ');
  }
}

$el.removeClass(makeRemoveClassHandler(/^foo-/));
//> [<div class=​"a b c foo">​</div>​]
 9
Author: abernier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-05 22:13:56

Http://www.mail-archive.com/[email protected]/msg03998.html dice:

...y .removeClass() eliminaría todas las clases...

Funciona para mí;)

Salud

 5
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-09 18:03:23

Estaba buscando una solución para exactamente el mismo problema. Para eliminar todas las clases que comienzan con el prefijo "fontid_" Después de leer este artículo escribí un pequeño plugin que estoy usando ahora.

(function ($) {
        $.fn.removePrefixedClasses = function (prefix) {
            var classNames = $(this).attr('class').split(' '),
                className,
                newClassNames = [],
                i;
            //loop class names
            for(i = 0; i < classNames.length; i++) {
                className = classNames[i];
                // if prefix not found at the beggining of class name
                if(className.indexOf(prefix) !== 0) {
                    newClassNames.push(className);
                    continue;
                }
            }
            // write new list excluding filtered classNames
            $(this).attr('class', newClassNames.join(' '));
        };
    }(fQuery));

Uso:

$('#elementId').removePrefixedClasses('prefix-of-classes_');
 2
Author: Pawel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-14 20:18:31

Un enfoque que usaría usando construcciones jQuery simples y funciones de manejo de matrices, es declarar una función que toma el id del control y el prefijo de la clase y elimina todas las clases. El código se adjunta:

function removeclasses(controlIndex,classPrefix){
    var classes = $("#"+controlIndex).attr("class").split(" ");
    $.each(classes,function(index) {
        if(classes[index].indexOf(classPrefix)==0) {
            $("#"+controlIndex).removeClass(classes[index]);
        }
    });
}

Ahora esta función se puede llamar desde cualquier lugar, un clic del botón o desde el código:

removeclasses("a","bg");
 2
Author: nhahtdh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-12 06:27:41

Sé que es una vieja pregunta, pero encontré una nueva solución y quiero saber si tiene desventajas?

$('#a')[0].className = $('#a')[0].className
                              .replace(/(^|\s)bg.*?(\s|$)/g, ' ')
                              .replace(/\s\s+/g, ' ')
                              .replace(/(^\s|\s$)/g, '');
 1
Author: Jan.J,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-28 06:54:55

La respuesta de Prestaul fue útil, pero no funcionó para mí. La forma de jQuery de seleccionar un objeto por id no funcionó. Tuve que usar

document.getElementById("a").className

En lugar de

$("#a").className
 0
Author: Brad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-12 01:19:49

También uso el guion'-' y los dígitos para el nombre de la clase. Así que mi versión incluye'\d- '

$('#a')[0].className = $('#a')[0].className.replace(/\bbg.\d-*?\b/g, '');
 0
Author: Jamland,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-19 20:10:43
(function($)
{
    return this.each(function()
    {
        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(' '));
    });
})(jQuery);
 0
Author: Rob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-19 02:47:39

En una línea ... Elimina todas las clases que coinciden con una expresión regular someRegExp

$('#my_element_id').removeClass( function() { return (this.className.match(/someRegExp/g) || []).join(' ').replace(prog.status.toLowerCase(),'');});
 0
Author: Adam111p,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-03 11:23:14
$("#element").removeAttr("class").addClass("yourClass");
 -6
Author: majorsk8,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-13 14:42:46