Beginnerprogrammer Beginnerprogrammer - 5 months ago 35
jQuery Question

jQuery - removeClass that starts with

Now I want to set different classes for different zoom levels in google-maps. Now it only adds the class and does not removes the class which starts with

zoom-
what am I doing wrong here? :

// setMarkerSize by different zoomLevels
if (z === 16) { $('.marker').removeClass("[className^='zoom-']").addClass('zoom-16'); }
if (z === 17) { $('.marker').removeClass("[className^='zoom-']").addClass('zoom-17'); }
if (z === 18) { $('.marker').removeClass("[className^='zoom-']").addClass('zoom-18'); }

Answer

removeClass() takes class names only, not selectors.

You can do this instead:

var $el = $('.marker');
var classList = $el.attr('class').split(' ');

$.each(classList, function(id, item) {
    if (item.indexOf('zoom-') == 0) $el.removeClass(item);
});

$el.addClass('zoom-' + z); // zoom-16, zoom-17, zoom-18 etc.
Comments