i'm trying add/remove class using javascript. (please don't post jquery, because that's irrelevant.) came upon this answer, suggested using regular expression remove class. here's code:
function removeclass(ele, cls) { if (hasclass(ele, cls)) { var reg = new regexp('(\\s|^)' + cls + '(\\s|$)'); ele.classname = ele.classname.replace(reg, ' '); } }
i'm going adding , removing same class. problem is, how ever many times that, that's how many spaces added class name. example, if add , remove class 5 times, there 5 spaces between 2 class names.
how can prevent spaces coming?
code snippet
var mydiv = document.getelementbyid('mydiv'), par = document.getelementbyid('par'); mydiv.addeventlistener('click', function() { if (hasclass(mydiv, 'trythis')) { removeclass(mydiv, 'trythis'); } else { addclass(mydiv, 'trythis'); } console.log(mydiv.classname); }); function hasclass(ele, cls) { return ele.classname.match(new regexp('(\\s|^)' + cls + '(\\s|$)')); } function addclass(ele, cls) { if (!hasclass(ele, cls)) ele.classname += " " + cls; } function removeclass(ele, cls) { if (hasclass(ele, cls)) { var reg = new regexp('(\\s|^)' + cls + '(\\s|$)'); ele.classname = ele.classname.replace(reg, ' '); } }
#mydiv { width: 100px; height: 100px; background-color: green; } .trythis { border: 2px solid orange; }
<div id="mydiv" class="hello">click me</div> <p id="par"></p>
there's 2 solutions. first (and easiest) use classlist. downfall solution won't able keep support browsers older implementation.
as second solution, keeps support old browsers , extends off regex solution, i'd suggest passing function replace
checks if both sides of class name whitespace. if are, return ' '
otherwise return ''
.
function removeclass(ele, cls) { if (hasclass(ele, cls)) { var reg = new regexp('(\\s|^)' + cls + '(\\s|$)'); ele.classname = ele.classname.replace(reg, function(match) { if (match.match(/^\s.+\s$/) !== null) { return ' '; } else { return ''; } }); } }
edit: there's option of using shim, sham, shiv, polyfill, etc.
Comments
Post a Comment