Skip to content Skip to sidebar Skip to footer

Removeclass Function Doesn't Work Properly

I wrote functions that allow the user to select and de select divs by clicking on them. Now, what i was trying to do was a function that, once pressed a, deselects everything, but

Solution 1:

Try changing that for loop:

for (var i = selected.length; --i >= 0; removeClass(selected[i], 'selected'));

The return value from getElementsByClassName() is a NodeList, not an array, and it's "live". That means that as you change the DOM by removing the class, you're changing the list too.

By going backwards, you avoid the problem. You could also do this:

while (selected.length) removeClass(selected[0], 'selected');

By the way the regex you're using to remove the classes could be simpler:

functionremoveClass(ele,cls) {
    var reg = newRegExp('\\b' + cls + '\\b', 'g');
    ele.className=ele.className.replace(reg,' ');
}

In a JavaScript regular expression, \b means "word boundary". Also there's no point calling hasClass() because the replacement just won't do anything if the class string isn't present.

edit — It's pointed out in a comment that this doesn't work for class names with embedded hyphens, a common convention. If you need to deal with that, then I think this would work:

functionremoveClass(ele,cls) {
    var reg = newRegExp('\\b' + cls.replace(/-/g, '\\b-\\b') + '\\b', 'g');
    ele.className=ele.className.replace(reg,' ');
}

or some variation on that theme.

Post a Comment for "Removeclass Function Doesn't Work Properly"