5 ms·
Perhaps I'm being a bit dense (I've done prettymuch no front-end JavaScript), but since className gives a single string with class names separated by spaces[1],
by jackmaney 12y ago
Perhaps I'm being a bit dense (I've done prettymuch no front-end JavaScript), but since className gives a single string with class names separated by spaces[1], won't
document.getElementById('foo').className =
document.getElementById('foo').className.replace(/^bold$/, '');
fail if the element in question has more than one class? In that case, you'd need to get the className attribute, split it by spaces, do the replacement in the resulting array, and then join back and assign, I believe.
[1]: https://developer.mozilla.org/en-US/docs/Web/API/Element.className https://developer.mozilla.org/en-US/docs/Web/API/Element.cla...
- sesutton 12y agoYou're right it will only work for one class. This is actually a perfect example of jQuery smoothing out the rough edges for you. I think the split method would work (provided you remember to split with \s instead of just space). It actually took me a while to come up with a regex replace that won't break in some corner cases ( I think) document.getElementById('foo').className = document.getElementById('foo').className.replace(/(\s|^)foo(\s|$)/, ' '); \b is out because it matches - and would kill stuff like foo-bar.
- cema 12y agoSubstitute \bbold\b for ^bold$ -- a potentially introduced extra space in the class name (string) should not matter.