Reputation: 33
var divfoo=document.getElementById("foo");
divfoo.className=" css-class css-class2 ";
divfoo.className=divfoo.className.replace(" css-class2 ", "");
The above code works. but I would like to make changes to last line of above code which is using replace method. Instead of writing the code like above, I would like to know why doesn't it work when written like below.
var divfoo=document.getElementById("foo");
divfoo.className=" css-class css-class2 ";
divfoo.className.replace(" css-class2 ", "");
Why should one assign to "divfoo.className" when applying replace method to the same "divfoo.className", why can't we just apply method directly like above code did?
Because of this should I hate javascript for not being logical?
enter code here
Upvotes: 0
Views: 535
Reputation: 11273
Element.className
is a plain string representation of class HTML attribute.
String.replace
method does not change the source string that is called on, just returns the result of replacement procedure.
If you want more "logical / functional" approach, look at Element.classList interface, namely the remove
method.
Upvotes: 1