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/

2 Answers 2

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
})
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

This is work too , But many classes added by jQuery before loaded :D , Thanks anyway :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.