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.

rishabh c
  • 39
  • 3
  • 1
    Possible duplicate of [Simple Javascript Replace not working](http://stackoverflow.com/questions/10863257/simple-javascript-replace-not-working) – Patrick Evans Apr 26 '16 at 11:20

4 Answers4

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"," ");
fbid
  • 1,570
  • 2
  • 18
  • 29
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

user3297291
  • 22,592
  • 4
  • 29
  • 45
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"," ");
}
jcubic
  • 61,973
  • 54
  • 229
  • 402
0

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

$("#cross").removeClass("anim");
Kirankumar Dafda
  • 2,354
  • 5
  • 29
  • 56