0

I want to remove matching class like type-one before adding new class like type-two

HTML :

<div class="demo test">
    <span>One</span>
    <span>Two</span>
    <span>Three</span>
</div>

jQuery :

$(document).on("click" ,".demo > span", function(){
        $(this).addClass("active").siblings().removeClass("active");


        $(this).parents(".demo").removeClass(function(i, c){
            return c.match(/type-[a-z]{0,5}/);
        })

        $(this).parents(".demo").addClass("type-"+$(this).text().toLowerCase());

})

My code is still adding and adding , cant remove the old matching class.

What I am doing wrong ?

Demo : http://jsfiddle.net/X5JxV/

l2aelba
  • 21,591
  • 22
  • 102
  • 138

2 Answers2

1

c.match(/type-[a-z]{0,5}/) is returning an array with one element.

You need to specify an index, i.e. c.match(/type-[a-z]{0,5}/)[0], but first you should check that a match as occurred, otherwise an error will be thrown.

$(this).parents(".demo").removeClass(function(i, c){
    var m = c.match(/type-[a-z]{0,5}/);
    return m ? m[0] : m
})
MikeM
  • 13,156
  • 2
  • 34
  • 47
1

What about this:

$(document).on("click" ,".demo > span", function(){
    $(this).addClass("active").siblings().removeClass("active");
    $(this).parents(".demo").removeClass().addClass("demo type-" + $(this).text().toLowerCase());
});

Here we remove all class names including demo and then reset it again with new type-xxx class.

dfsq
  • 191,768
  • 25
  • 236
  • 258