1

I tried a method to remove class of an element in JavaScript but it did not work can you all explain why.

function del() 
{
cross.className.replace("anim"," ");
}

cross is a element saved in a variable.

1

4 Answers 4

2

The strings replace() method returns a new string with the new value. It doesn't modify the original string.

Here is a simple example:

var str = "Hello World!";
var res = str.replace("World", "Foo");

console.log(str);  // prints Hello World!
console.log(res);  // prints Hello Foo!

So, in your specific case, in order to make it work you have to assign the new string to cross.className like in the code below:

cross.className = cross.className.replace("anim"," ");
Sign up to request clarification or add additional context in comments.

Comments

2

If you don't have to support really old browsers, you can also use the classList property:

cross.classList.remove("anim");

Creating your own methods for adding, removing and replacing classes can go wrong very easily. E.g.: what should happen when another class contains the substring "anim"? By using the readily available methods in the Element class, you're making your job a lot easier.

More on classList: https://developer.mozilla.org/en/docs/Web/API/Element/classList

Comments

0

You need to assign the value to class, because replace return new string with replaced text

function del() {
    cross.className = cross.className.replace("anim"," ");
}

Comments

0

Either you can use jQuery to remove class from specific element by its id

$("#cross").removeClass("anim");

Comments

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.