Remove classname from element with javascript

爷,独闯天下 提交于 2019-12-18 10:43:19

问题


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);
})​

回答1:


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

)




回答2:


Don't forget about classList.

el.classList.remove('boop');

http://jsfiddle.net/yXQL3/




回答3:


foo.className = foo.className.replace( /(?:^|\s)bar(?!\S)/ , '' );

or with jQuery (which you seem to be using):

foo.removeClass( 'bar' );



回答4:


There is also a solution which use the word boundary metacharacter \b:

foo.className.replace(/\bbar\b/g ,'');

This can suite somebody, but be aware the word boundary occurs also between a word character [A-Za-z0-9_] and the dash - character. Therefore a class name e.g. 'different-bar-class' would also be replaced resulting in 'different--class'. However, as opposed to the above solutions, the "\b" solution doesn't remove the whitespace character \s before the class name, which may be desired, so a string e.g. 'firstbar bar' will end up as 'firstbar '.



来源:https://stackoverflow.com/questions/9959781/remove-classname-from-element-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!