Reputation: 39
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.
Upvotes: 1
Views: 276
Reputation: 23372
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
Upvotes: 2
Reputation: 2384
Either you can use jQuery to remove class from specific element by its id
$("#cross").removeClass("anim");
Upvotes: 0
Reputation: 1570
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"," ");
Upvotes: 2
Reputation: 66478
You need to assign the value to class, because replace return new string with replaced text
function del() {
cross.className = cross.className.replace("anim"," ");
}
Upvotes: 0