I would like to remove an array element from my todo type app. Adding is fine using element.push()
. The remove button is in a template literal in the for loop. So I don't quite understand how to remove the element. I do now of another method using node.parentNode.removeChild(node);
but as this is an array data method I assume the approach would be different. This is more of a learning/playground project for me. My code so far is:
const main = document.querySelector('.app');
const header = document.createElement('DIV');
const hero = document.createElement('DIV');
const heading = document.createElement('H1');
heading.textContent = 'Heading Tag';
main.before(heading);
const data = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday"
];
const headerElement = () => {
header.textContent = 'Header';
header.classList.add('header');
header.innerHTML = '<div class="innerElement">Inner</div>';
header.setAttribute(
"style", "font-size: 32px; font-style: bold; background-color:#ff0000; color: white; width: 100%; height: 200px; padding: 20px; font-family: sans-serif");
main.append(header);
}
const heroElement = () => {
hero.textContent = 'Hero';
hero.classList.add('hero');
hero.innerHTML = '<div class="innerElement">Inner Element</div>';
hero.setAttribute(
"style", "font-size: 32px; font-style: bold; background-color:#000000; color: white; width: 100%; height: auto; padding: 20px; font-family: sans-serif");
main.append(hero);
}
const itemArray = (ele) => {
let items = '';
for (let i = 0; i < ele.length; i++) {
items += `<li>${ele[i]}</li><button type='button' id='removeItem'>Remove Item</button>`;
}
return items;
}
const layOut = () => {
const ui = headerElement() + heroElement();
}
layOut();
const addItemFunction = () => {
const addButton = document.getElementById('addButton');
const input = document.getElementById('input').value;
data.push(input);
htmlInside(data);
}
const removeItemFunction = (index) => {
const removeButton = document.getElementById('removeButton');
data.pop(data);
htmlInside(data);
}
const htmlInside = (data) => {
let getHtml = `
<ul>
${itemArray(data)}
</ul>
<input type='input' id="input" required></input><button type='button' id='addButton'>Add item</button><button id='removeButton'>Remove item</button>
`
document.querySelector('.hero').innerHTML = getHtml;
addButton.addEventListener('click', () => {
addItemFunction();
});
removeButton.addEventListener('click', () => {
removeItemFunction();
});
}
htmlInside(data);
let removeItem = document.getElementById('removeItem');
removeItem.addEventListener('click', (data) => {
for (let i = 0; i < removeItem.length; i++) {
data.splice(i, 1);
}
});
I was thinking maybe using indexOf
?