How do I delete an <li> on click with vanilla javascript? - javascript

I'm having trouble finding the right syntax to use to delete an element. I have a list item that I generate with a form that I want to also be deleted when I click on it. Here is my current javascript code:
// add to do items
let todoList = [];
function addTodo(item){
todoList.push(item);
//display item
}
const addButton = document.querySelector('.btn__display');
const formInput = document.querySelector('.addItem');
const listItems = document.querySelectorAll('li');
addButton.addEventListener('click', function(){
const todoUl = document.querySelector('ul');
const todoLi = document.createElement('li');
todoLi.textContent = formInput.value;
todoList.push(formInput.value);
todoUl.appendChild(todoLi);
formInput.value = '';
});
So far I can add an item to my todo list but how do I go about deleting it with a click?

You can add an onclick listener to the newly created li element to remove it when clicked:
todoLi.onclick = (e) => e.target.remove();
// add to do items
let todoList = [];
function addTodo(item) {
todoList.push(item);
//display item
}
const addButton = document.querySelector('.btn__display');
const formInput = document.querySelector('.addItem');
const listItems = document.querySelectorAll('li');
addButton.addEventListener('click', function() {
const todoUl = document.querySelector('ul');
const todoLi = document.createElement('li');
todoLi.textContent = formInput.value;
todoLi.onclick = (e) => e.target.remove();
todoList.push(formInput.value);
todoUl.appendChild(todoLi);
formInput.value = '';
});
<button class="btn__display">btn__display</button>
<input type="text" class="addItem">
<ul></ul>

Similar to Luis's answer, you can do the following:
// add to do items
let todoList = [];
function addTodo(item){
todoList.push(item);
//display item
}
const addButton = document.querySelector('.btn__display');
const formInput = document.querySelector('.addItem');
addButton.addEventListener('click', function(){
const todoUl = document.querySelector('ul');
const todoLi = document.createElement('li');
todoLi.textContent = formInput.value;
todoList.push(formInput.value);
todoUl.appendChild(todoLi);
formInput.value = '';
todoLi.addEventListener('click', function () {
this.remove();
});
});
The difference being that we are instead adding the event listener with a function where this will be set to the list item.
https://jsfiddle.net/gy9cLum3/

Try with this code:
<ul>
<li onclick="remove(this)">lorem</li>
</ul>
<script>function remove(elem) { elem.parentElemet.removeChild(elem); } </script>

Related

How do I remove an object from an array on click? Javascript

I'm adding hours and dates which are displayed in a list and then pushing the values to an array.
A button is created next to each list item and I want to be able to remove the specific list item on click.
I've tried splice, slice and remove but I'm not able to make it work as I want.
let vacationList = [];
$('#add').click(function(e){
e.preventDefault();
let vacationHours = $('#vacationHours').val();
let vacationDates = document.querySelector("#vacationDates").value;
const li = document.createElement("li");
li.innerText = vacationHours + "h - " + vacationDates;
const button = document.createElement("button");
button.className = "fa fa-minus-circle";
const ul = document.querySelector(".list");
ul.appendChild(li);
li.appendChild(button);
button.addEventListener('click', (e) => {
e.preventDefault()
??
});
vacationList.push({vacationHours: Number(vacationHours), vacationDates: vacationDates});
Element.remove() should work for the dom element. If you want also remove from array please provide the adding to array code.
$('#add').click(function(e) {
e.preventDefault();
let vacationHours = $('#vacationHours').val();
let vacationDates = document.querySelector("#vacationDates").value;
const li = document.createElement("li");
li.innerText = vacationHours + "h - " + vacationDates;
const button = document.createElement("button");
button.className = "fa fa-minus-circle";
const ul = document.querySelector(".list");
ul.appendChild(li);
li.appendChild(button);
button.addEventListener('click', (e) => {
e.preventDefault()
this.closest("li").remove();
});
});

How to create a dynamic list, which removes deleted items from an array in JS?

I have created a list, which creates a new paragraph, with the value of the input field and adds the value of the input field into an array, if the add-Button is pressed. Each paragraph has a delete Button, which removes the paragraph visually, if pressed. Now I want that the Input of the paragraph also gets removed from the array.
For example lets say, that the array usernames includes usernames[1] = Lukas, usernames[2] = Martin, usernames[3] = Bob and I want to delete the paragraph, which includes Martin.
How can I create a function, where the paragraphs content also automatically gets removed from the array usernames. I would be very thankful for some help.
Here is my code:
let name = document.getElementById('name');
let addButton = document.getElementById('button');
let output = document.getElementById('output')
let usernames = [];
addButton.addEventListener('click', function() {
usernames.push(document.getElementById('name').value)
console.log(usernames)
let paragraph = document.createElement('ul')
paragraph.innerText = document.getElementById('name').value
output.appendChild(paragraph)
let deleteButton = document.createElement('button')
deleteButton.innerHTML = "X"
paragraph.appendChild(deleteButton)
deleteButton.addEventListener('click', function() {
output.removeChild(paragraph)
})
})
You can find an element in the array by name and remove it from there:
const usernameToRemove = usernames.indexOf(name => name === paragraph.innerText);
usernames.splice(usernameToRemove, 1);
let name = document.getElementById('name');
let addButton = document.getElementById('button');
let output = document.getElementById('output')
let usernames = [];
addButton.addEventListener('click', function() {
usernames.push(document.getElementById('name').value)
console.log(usernames)
let paragraph = document.createElement('ul')
paragraph.innerText = document.getElementById('name').value
output.appendChild(paragraph)
let deleteButton = document.createElement('button')
deleteButton.innerHTML = "X"
paragraph.appendChild(deleteButton)
deleteButton.addEventListener('click', function() {
const usernameToRemove = usernames.indexOf(name => name === paragraph.innerText);
usernames.splice(usernameToRemove, 1);
output.removeChild(paragraph)
})
})
<input id="name">
<button id="button">button</button>
<div id="output">output</div>
Every time the event handler to delete an item is called, just collect all of the text of each item and convert it into an array.
del.addEventListener('click', function() {
this.closest('li').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
/*
This removes an <li>, if you don't change your "paragraph" then
change 'li' to 'ul'
*/
const user = document.getElementById('user');
const add = document.querySelector('.add');
const list = document.querySelector('.list')
let usernames = [];
add.addEventListener('click', function() {
let name = user.value;
user.value = '';
usernames.push(name);
console.log(usernames);
const item = document.createElement('li');
item.textContent = name+' ';
list.append(item);
const del = document.createElement('button');
del.textContent = "X";
item.append(del);
del.addEventListener('click', function() {
this.closest('li').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
});
<input id='user'><button class='add'>ADD</button>
<ul class='list'></ul>
Thank you for your answers, but unfortunately the inner Text of the delete Button gets added to the array content, if something gets deleted, because it is part of the 'li' component. I simply created a div which includes the name and the delete Button to solve the problem. But nevertheless thank you for your help. Thats the working code:
const user = document.getElementById('user');
const add = document.querySelector('.add');
const list = document.querySelector('.list')
let usernames = [];
add.addEventListener('click', function() {
let name = user.value;
user.value = '';
usernames.push(name);
console.log(usernames);
const paragraph = document.createElement('div')
paragraph.style.display = 'flex'
const item = document.createElement('li');
item.textContent = name + ' ';
list.append(paragraph);
paragraph.append(item)
const del = document.createElement('button');
del.textContent = "X";
paragraph.append(del);
del.addEventListener('click', function() {
this.closest('div').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
});

How make Total cart without "location.reload();"

i have a problem
In my cart, i want to recalculta the amount total off quantity and price
without using
location.reload();
You can find here a bit of my code to understand how i created all my elements
let productLocalStorage = JSON.parse(localStorage.getItem("products"));
let cartItems = document.getElementById('cart__items');
/*This Function is here because of the unknown number of products in the cart **
**so i can reuse the creation of all elements if i need **
**All the JS elements have their own description to make the code more understandble*/
const cartProducts = (productStorage) => {
console.log(productStorage.product);
//------Create constant article who gonna contein all my elements------
let article = document.createElement('article');
article.classList.add('cart__item');
article.setAttribute( "data-id", productStorage.id);
let cartDivImg = document.createElement('div');
cartDivImg.classList.add('cart__item__img');
let cartImg = document.createElement('img');
cartImg.setAttribute('src', productStorage["imageUrl"]);
cartImg.setAttribute('alt', productStorage["alt"]);
let cartDivContent = document.createElement('div');
cartDivContent.classList.add('cart__item__content');
let cartDivContentTitle = document.createElement('div');
cartDivContentTitle.classList.add('cart__item__content__titlePrice');
let cartName = document.createElement('h2');
cartName.textContent = productStorage.name;
let cartColorName = document.createElement('h2');
cartColorName.textContent = productStorage.color;
let cartPrice = document.createElement('p');
cartPrice.textContent = productStorage.price + " €";
let cartDivSettings = document.createElement('div');
cartDivSettings.classList.add('cart__item__content__settings');
let cartDivQuantity = document.createElement('div');
cartDivQuantity.classList.add('cart__item__content__settings__quantity');
let cartQuantityP = document.createElement('p');
cartQuantityP.textContent = "Qté : ";
let cartQuantityInput = document.createElement('input');
cartQuantityInput.setAttribute("type","number");
cartQuantityInput.setAttribute("name","itemQuantity");
cartQuantityInput.classList.add('itemQuantity');
cartQuantityInput.setAttribute("min","1");
cartQuantityInput.setAttribute("max","100");
cartQuantityInput.setAttribute("value", productStorage.quantity);
let cartItemDelete = document.createElement('div');
cartItemDelete.classList.add('cart__item__content__settings__delete');
let CartDeleteP = document.createElement('p');
CartDeleteP.textContent = "Supprimer";
CartDeleteP.classList.add('deleteItem');
//Create all the elements
article.appendChild(cartDivImg);
cartDivImg.appendChild(cartImg);
article.appendChild(cartDivContent);
cartDivContent.appendChild(cartDivContentTitle);
cartDivContentTitle.appendChild(cartName);
cartDivContentTitle.appendChild(cartColorName);
cartDivContentTitle.appendChild(cartPrice);
cartDivContent.appendChild(cartDivSettings);
cartDivSettings.appendChild(cartDivQuantity);
cartDivQuantity.appendChild(cartQuantityP);
cartDivQuantity.appendChild(cartQuantityInput);
cartDivSettings.appendChild(cartItemDelete);
cartItemDelete.appendChild(CartDeleteP);
cartItems.appendChild(article);
}
if (productLocalStorage === null){
emptyCart();
}
// Loop "forEach" who create all the elements i need in my cart
else{
productLocalStorage.forEach(productLocalStorage => {
cartProducts(productLocalStorage);
});
}
let products = JSON.parse(localStorage.getItem("products"));
function removeItem() {
let removeBtn = document.querySelectorAll(".deleteItem");
for (let i = 0; i < removeBtn.length; i++) {
removeBtn[i].addEventListener("click", (event) => {
event.preventDefault();
let articleSupp = removeBtn[i].closest("article");
articleSupp.remove();
calculateTotal();
totalArtQte();
deleteItemSelected(i);
alert("This item will be delete from your cart !");
location.reload();
// Actualising the total amount of item in the cart
});
//This Function is here to remove my item in my local storage
function deleteItemSelected(index) {
products.splice(index, 1);
localStorage.setItem("products", JSON.stringify(products));
}
}
}
And here is my remove function
as you can see, i try to recall my calculateTotal() and my totalArtQte() function
to recalculate the amount total off quantity and price, but my function are only recall
if i use location.reload(); is it normal ? Do you know what can i do ?
I have to use only JavaScript
Thank you for those who gonna read / answer to my question
you don't have to call whole thing again or location.reload(). try to find the events when you want to re-calculate the cart. e.g. on
new item add
updated existing quantity
delete items
function getProductById(id) {
let index = productLocalStorage.findIndex( x => x.id == id );
return productLocalStorage[index];
}
// on new item
function addProduct(product) {
cartProducts(product);
productLocalStorage.push(product);
// update your cart total/whatever by looping through "productLocalStorage"
}
// on quantity change
cartQuantityInput.addEventListener('change', function($event) {
let product = getProductById(productStorage.id);
product.quantity = $event.target.value;
// update your cart total/whatever by looping through "productLocalStorage"
});
// on delete
let deleteButton = document.createElement('button');
deleteButton.innerHTML = 'Delete';
deleteButton.addEventListener('click', function deleteProductEvent($event) {
productLocalStorage = productLocalStorage.filter(function( product ) {
return product.id !== $event.target.parentElement.getAttribute('data-id');
});
this.removeEventListener('click', arguments.callee, false);
$event.target.parentElement.remove();
// update your cart total/whatever by looping through "productLocalStorage"
});
PS: make sure your UI, "productLocalStorage" variable and localstorage are in sync.
this will be much easier if you implement this with MVC/MVVM framework like Angular

Loop through <li> and display list containing input value

I have a list of items like a todo list and i have a search input where i want users to search through the list'
I am using the keyup event and if input matches i am trying to use css to set the matched li to display:'' while the list items that do not match i want to set display:none.
so far i am able to console.log my results but cant effect changes to my li list as the css to set display none doesn't work.
here is my code below.
const Ul = document.querySelector('.clipBoard');
const search = document.querySelector('.search');
array.forEach((item) => {
let button = document.createElement('button');
button.className =
'list-group-item buttonLi';
button.innerText += item;
Ul.appendChild(button);
//Search function
search.addEventListener('keyup', () => {
let filterValue = search.value;
const li = Ul.querySelectorAll('.buttonLi');
for (let i = 0; i < li.length; i++) {
let List = li[i];
if (List.innerHTML.indexOf(filterValue) > -1) {
console.log(li[i].innerHTML);
li[i].style.display = '';
} else {
li[i].style.display = 'none';
}
}
});
I would suggest you to assign an id to each element using the index at that level:
array.forEach((item, INDEX) => {
let button = document.createElement('button');
var id = 'el-'+INDEX
button.setAttribute("id", id);
button.setAttribute("class", "list-group-item buttonLi");
button.innerText += item;
});
Then on your search function use that id to hide the elements
search.addEventListener('keyup', () => {
let filterValue = search.value;
const li = Ul.querySelectorAll('.buttonLi');
for (let i = 0; i < li.length; i++) {
let List = li[i];
if (List.innerHTML.indexOf(filterValue) > -1) {
console.log(li[i].innerHTML);
// something like that
var idToShow = '#el-'+i;
document.querySelector(idToShow).style.display = 'block';
} else {
// something like that
var idToHide = '#el-'+i;
document.querySelector(idToHide).style.display = 'none';
}
}
});
I did not test this code, just trying to point you to an eventual solution!
You could also do the filtering on your array then for each search you re-render your list!

how to make todolist remain after reload with local storage

i code this far but have no idea how to use localstorage so i dont have to lose my todolist in my browser when reload/refresh.
This is the code i have already set item to the local storage with savetodos function
var form = document.querySelector('form')
var ul = document.querySelector('ul')
var button = document.querySelector('#button');
var input =
document.querySelector('#item');
var clear =
document.querySelector('#clear');
var savedToDos = []
//this makes list item
var liMaker = text => {
var li = document.createElement('li');
li.textContent = text;
ul.insertBefore(li, ul.childNodes[0])
}
form.addEventListener('submit', function(e) {
e.preventDefault()
liMaker(input.value)
input.value = ''; }
);
clear.addEventListener('click', remove);
//function remove to remove list item
function remove(){
saveToDos();
while (ul.firstChild) {
ul.removeChild(ul.firstChild);
}
}
function saveToDos() {
var items =
ul.getElementsByTagName("li");
for (var i = 0; i < items.length; ++i) {
savedToDos.push(
items[i].innerHTML);
}
localStorage.setItem('savedValues', savedToDos);
}
<div class='container'>
<h1> New todo list</h1>
<form>
<input type='text' id='item'
required>
<ul id="myList"></ul>
<button id='button'>add</
button> </form>
<button id="clear">Clear</
button>
</div>
You can handle it as follows:
save input value to the localstorage when it's added
populate the list on page load if there are items storage in the localstorage
remove all items from the localstorage, when user click clear button
This is how it may look like:
<div className='container'>
<h1> New todo list</h1>
<form>
<input type='text' id='item' required>
<ul id="myList"></ul>
<button id='button'>add</button>
</form>
<button id="clear">Clear</button>
</div>
<script>
var form = document.querySelector('form')
var ul = document.querySelector('ul')
var button = document.querySelector('#button');
var input = document.querySelector('#item');
var clear = document.querySelector('#clear');
var savedToDos = []
//this makes list item
var liMaker = text => {
var li = document.createElement('li');
li.textContent = text;
ul.insertBefore(li, ul.childNodes[0])
}
form.addEventListener('submit', function(e) {
e.preventDefault()
liMaker(input.value)
saveToDo(input.value)
input.value = '';
});
clear.addEventListener('click', remove);
//function remove to remove list item
function remove(){
while (ul.firstChild) {
ul.removeChild(ul.firstChild);
}
localStorage.removeItem('savedValues')
}
function saveToDo(item) {
var storedItems = localStorage.getItem('savedValues');
storedItems = storedItems ? JSON.parse(storedItems) : [];
storedItems.push(item);
localStorage.setItem('savedValues', JSON.stringify(storedItems))
}
// populate the list on page load from localStorage
var storedItems = localStorage.getItem('savedValues');
if (storedItems) {
JSON.parse(storedItems).forEach(function(item) {
liMaker(item)
})
}
</script>

Categories

Resources