I found the following regex from another Stack Overflow question: Change an element's class with JavaScript
And have used it in part of my script with success, however in another it seems to be failing.
I threw together a very minimalist test case on jsFiddle, and it is also failing:
http://jsfiddle.net/ew47Y/1/
HTML:
<div class="foo" id="foo">
hello
</div>
JS:
$(document).ready(function(){
foo = document.getElementById('foo');
foo.className += ' bar foobar';
alert(foo.className);
foo.className.replace( /(?:^|\s)bar(?!\S)/ , '' )
alert(foo.className);
})
Use the classList. remove() method to remove a class from a div element, e.g. box. classList. remove('my-class') .
To remove a class from an element, you use the remove() method of the classList property of the element.
The removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.
In JavaScript, an element can only be deleted from its parent. To delete one, you have to get the element, find its parent, and delete it using the removeChild method.
That's because replace
doesn't actually modify the string you call it on; rather, it returns a new string. So:
foo.className = foo.className.replace( /(?:^|\s)bar(?!\S)/ , '' )
(By the way, you don't actually need to do this in raw JavaScript, since jQuery objects offer a removeClass
method: http://api.jquery.com/removeClass/. So you could write:
$('#foo').removeClass('bar');
or:
$(foo).removeClass('bar');
)
Don't forget about classList
.
el.classList.remove('boop');
http://jsfiddle.net/yXQL3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With