Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove classname from element with javascript

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);
})​
like image 326
Chris Sobolewski Avatar asked Mar 31 '12 21:03

Chris Sobolewski


People also ask

How do I remove a class from a div?

Use the classList. remove() method to remove a class from a div element, e.g. box. classList. remove('my-class') .

How do I get rid of className Dom?

To remove a class from an element, you use the remove() method of the classList property of the element.

What is removeClass in JavaScript?

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.

How do you remove an element in JavaScript?

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.


2 Answers

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'); 

)

like image 200
ruakh Avatar answered Sep 20 '22 15:09

ruakh


Don't forget about classList.

el.classList.remove('boop');

http://jsfiddle.net/yXQL3/

like image 20
Derek Reynolds Avatar answered Sep 19 '22 15:09

Derek Reynolds