I'm trying to splice an array when an element is clicked. When I console.log the new array it's irregular and sometimes removes the wrong array element and the last index will never be removed. Any one here with a good explanation to this?
var container = document.getElementById('container'),
notDone = document.getElementsByClassName('notDone'),
deleting = document.getElementsByClassName('delete'),
div,
remove,
i,
toDo = [
'One',
'Two',
'öäå'],
for(i = 0; i < toDo.length; i++){
div = document.createElement('div');
div.innerHTML = toDo[i];
div.className = 'notDone';
remove = document.createElement('div');
remove.innerHTML = '<p>Remove</p>';
remove.setAttribute("data-id", i);
remove.className = 'delete';
container.appendChild(div);
div.appendChild(remove);
notDone[i].addEventListener('click', function(){
if(this.classList.contains('notDone')){
this.className = 'done';
}else{
this.className = 'notDone';
}
});
deleting[i].addEventListener('click', function(event){
event.stopPropagation();
var shouldDelete = this.getAttribute("data-id");
console.log('va' + shouldDelete);
toDo.splice(shouldDelete, 1);
this.parentNode.remove();
console.log(toDo);
});
}
var check = document.getElementById('check');
check.addEventListener('click', function(){
console.log(toDo + ' checking array')
});