简体   繁体   中英

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.

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"," ");

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. Eg: 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

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

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

您可以使用jQuery通过其ID从特定元素中删除类

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM