Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  176] [ 4]  / answers: 1 / hits: 31521  / 12 Years ago, sat, march 31, 2012, 12:00:00

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

More From » regex

 Answers
5

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


)


[#86481] Friday, March 30, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
;