I am using vanilla JS, I can push to the array, and remove last item from array. Next I am trying to remove array item on click. The function I have created below kind of works, but it's not correct? Where am I going wrong? I don't want to remove the item from the DOM, I would rather remove the item from the array and then update the UI state.
So code below:
let someData = [
'This is some serious data part 2',
'This is some serious data part 3',
'This is some serious data part 4',
];
const loopIt = (data) => {
let item = '';
for (let i = 0; i < data.length; i++) {
item += `<li>${data[i]}<button class='testBtn'>Remove ${i}</button></li>`;
}
return item;
}
let getHtml = () => {
domElem.selector.innerHTML = loopIt(someData);
}
const clickEvents = () => {
domElem.button.addEventListener ('click', function () {
let inputData = domElem.input.value;
if (inputData.length > 0) {
someData.push(inputData);
} else {
alert('no input');
}
getHtml();
});
domElem.buttonRemove.addEventListener ('click', function () {
someData.pop();
getHtml();
});
}
const removeArrayItem = () => {
let queryS = document.querySelectorAll('.testBtn');
for (let i = 0; i < queryS.length; i++) {
let index = queryS[i];
index.addEventListener('click', function () {
alert(i);
someData.splice(i, 1);
console.log(someData);
getHtml();
});
};
}
const init = () => {
getHtml();
elemAttributes();
clickEvents();
removeArrayItem();
}
let initialise = init();
My removeArrayItem
is
- 1 - querying the dom
(let queryS = document.querySelectorAll('.testBtn');)
- 2 - looping over the array,
returning the index value (i)
(Loop function)
- 3 - adding event listener to each element in the array
- 4 - removing the array item (Splice method) -
- 5 - updating the UI (getHtml() function);
But something somewhere is going wrong? as the UI does not update after first click.
If I push items I can't remove them on click.