0

I try to use this code in my javascript program:

this.classList.remove(RF.DangerClass);

Where RF.DangerClass is global variable. But I get error -

InvalidCharacterError: String contains an invalid character

What's wrong? I can't use variable in this statement?

RF.DangerClass contain this string: uk-form-danger uk-animation-shake

What should I do if need to remove two classes?

3
  • Yes, you can use a variable there. What does RF.DangerClass contain? Commented May 13, 2018 at 6:55
  • I think I get the source of error - this variable contains "uk-form-danger uk-animation-shake". So the space is wrong character? Commented May 13, 2018 at 6:58
  • Yes, that is the cause of the InvalidCharacterError Commented May 13, 2018 at 7:10

1 Answer 1

1

If the given class name may contain invalid characters (such as spaces), then first check if the class name is present before calling remove. The remove function may fail if the specified class name has invalid characters.

var classNames = ['invalid class', 'other-class']

classNames.forEach(function(name) {
    if (this.classList.contains(name)) {
        this.classList.remove(name)
    }
})

If the class names are known to be valid, you can remove multiple items with:

this.classList.remove('class1', 'class2')
Sign up to request clarification or add additional context in comments.

2 Comments

what if I need to remove two or more classes?
Then you need to loop

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.