Remove classname from element with javascript

前端 未结 4 2011
忘掉有多难
忘掉有多难 2020-12-24 07:35

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, h

4条回答
  •  一生所求
    2020-12-24 08:16

    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 '.

提交回复
热议问题