I have implemented functions that enable users to select and deselect divs by clicking on them. However, I encountered an issue when trying to create a function that should deselect everything upon pressing a. Surprisingly, this function only deselects some of my divs instead of all. Here is the code snippet:
var divs = document.getElementsByClassName('fuori');
for(i = 0, j = divs.length; i < j; i++){
divs[i].addEventListener('click', function(){
if(!hasClass(this, 'selected')){
this.className = this.className + " selected";
} else {
removeClass(this, 'selected');
}
});
}
The 'removeClass' function looks like this:
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
And here's the 'deselectAll' function:
function deselectAll(){
var selected = document.getElementsByClassName('selected');
alert(selected.length);
for (i = 0; i < selected.length; i++){
removeClass(selected[i], 'selected');
}
}
While selecting and deselecting by clicking works smoothly, the issue arises when some divs are selected and then a is pressed, as it fails to deselect every div. How can I resolve this problem? And why does it occur in the first place?
Any assistance would be greatly appreciated!