rishabh c
rishabh c

Reputation: 39

Remove class of an element in Javascript using replace function

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

Answers (4)

user3297291
user3297291

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

Kirankumar Dafda
Kirankumar Dafda

Reputation: 2384

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

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

Upvotes: 0

fbid
fbid

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

jcubic
jcubic

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

Related Questions