Library Project - Updating the object when book is removed - javascript

Problem:
When the user creates a book, the information that is in the input fields will be displayed. There is a remove button that the user can click and it deletes the book. However, when I use filter() I'm just returning the book parameter, so what can I change about my deleteBook() to be able to delete a book? I don't want the UI to work but I just want the library array to update.
Repl: https://repl.it/#antgotfan/library
What I've tried:
I've tried manipulating the document and whenever the user clicked on the remove then it would be deleted but not update the object to show that it was actually deleted
// Variables
const addBook = document.querySelector("#add");
let library = [];
// Event Listeners
addBook.addEventListener("click", render);
document.addEventListener("click", deleteBook);
// Constructor
function Book(title, author, pages, isRead) {
this.title = title;
this.author = author;
this.pages = pages;
this.isRead = isRead;
}
// Prototypes
Book.prototype.toggleIsRead = function() {
if (this.isRead == "Read") {
this.isRead = "Not read";
} else {
this.isRead = "Read";
}
}
function deleteBook(event) {
if (event.target.id == "remove") {
library.filter(book => {
return book;
});
}
}
// Functions
function addBookToLibrary() {
let authorOfBook = document.querySelector("#author").value;
let bookTitle = document.querySelector("#book-title").value;
let numberOfPages = document.querySelector("#pages").value;
let status = document.querySelector("#isRead").value;
let newBook = new Book(bookTitle, authorOfBook, numberOfPages, status);
library.push(newBook);
return newBook;
}
function updateStatus() {
}
function emptyInputs() {
const inputs = Array.from(document.querySelectorAll("input"));
inputs.forEach(input => input.value = "");
}
function render() {
addBookToLibrary();
emptyInputs();
let newBook = library[library.length - 1];
let table = document.querySelector("table");
let createTr = document.createElement("tr");
table.appendChild(createTr);
createTr.innerHTML = `<td>${newBook.title}</td>
<td>${newBook.author}</td>
<td>${newBook.pages}</td>
<td><button class="table-buttons" id="not-read">${newBook.isRead}</button></td>
<td><button class="table-buttons" id="remove">Delete</button></td>`;
}
Error messages:
No errors but just not having an updated object to show what was kept or deleted.

Since the books are in an array you can use a function that takes the book properties like author, title etc
and then uses that info to find the book in the array and delete it.
let books = [{ title: "book1" }, { title: "book2" }];
console.log(books);
deleteBook("book2");
console.log(books);
function deleteBook(title) {
let i = books.findIndex(b => b.title == title);
books.splice(i, 1);
}
//Outputs
[ { title: 'book1' }, { title: 'book2' } ] //before delete called
[ { title: 'book1' } ] //after delete called

This soloution worked for me:
function deleteBook(event) {
if (event.target.id == "remove") {
const table = document.querySelector('table');
const tr = event.target.parentNode.parentNode;
table.removeChild(tr);
}
}
Basically, you grab the table and then remove the child node that had the event fired on it.
You can grab the table using the querySelector() function, and you may want to consider giving that table a unique id or something down the line.
const table = document.querySelector('table');
Then, you take the target of the event, which is the <button> element, and get it's grandparent by calling parentNode twice. The first parent is the <td> element, the next one is the <tr> element, which is what we want to remove from the table.
const tr = event.target.parentNode.parentNode;
Finally, you can call removeChild() on the <table> element and have it remove the row that the button was pushed from.
table.removeChild(tr);

Related

mapped button info is out of bounds

function AddDocument(Name, TTid) {
auth.onAuthStateChanged(user => {
if(user) {
const colUser = collection(fsinfo, 'User');
// goes to database colelction "user"
const colUser2 = doc(colUser, user.uid);
// goes to the document in colUser named "one"
const colUser3 = collection(colUser2, 'MoviesLiked');
whenSignedIn.hidden = false;
whenSignedOut.hidden = true;
setDoc(doc(colUser3, Name), {
movieliked: TTid,
})
}
else {
whenSignedIn.hidden = true;
whenSignedOut.hidden = false;
//userDetails.innerHTML = '';
console.log( "while logged out" );
console.log("notloggedin");
}
})
};
// query can either be a title or a tt id
function searchMovie(query) {
const url = `https://imdb8.p.rapidapi.com/auto-complete?q=${query}`;
fetch(url, options)
.then(response => response.json())
.then(data => {
var outname = null;
var outdetail = null;
const movieList = document.querySelector('.movielist');
movieList.addEventListener('click', handleClick);
const list = data.d;
//array of list with data from the movie search
//data.d is the specific datas that is outputted from the api
//list is an array that holds that data
console.log(list)
// ^ will output what list holds
const html = list.map(obj => {
const name = obj.l; // holds the name of movie
outname = name;
const poster = obj.i.imageUrl; // holds the poster, i is the image
const detail = obj.id
outdetail = detail;
return `
<section class="movie">
<img src="${poster}"
width = "500"
height = "800"/>
<h2>${name}</h2>
<section class = "details">${detail}</section>
<button type="button">Movie Details</button>
</section>
`;
}).join('');
// Insert that HTML on to the movie list element
function handleClick(e) {
if (e.target.matches('button')) {
const details = e.target.previousElementSibling;
details.classList.toggle('show');
AddDocument(outname, outdetail);
}
}
movieList.insertAdjacentHTML('beforeend', html);
document.getElementById("errorMessage").innerHTML = "";
})
.catch((error) => {
document.getElementById("errorMessage").innerHTML = error;
});
I have a function that will take search to an API call and then load the info from the API to a list.
It should then output said each of said list using list.map(obj) and each item will have a name, poster, and a button attached to it.
Outside the map I have a function that will react when the button is pressed which will toggle and then load the details of the movie to a database in the AddDocument function. My issue is that I am not sure how to make it so that when the button is pressed AddDocument will add whichever obj.name is connected to the button.
Currently, AddDocument will only add the last item in the list and not the item that I pressed the button for.
I know that it is because the function is outside where the mapping is done, and thus the items that are held in outname, and outdetail are the last items that have been mapped. But I just can't figure out a way to make the button press add the correct document to the database.
(I really didn't want to ask this, but I had spent hours thinking and searching and couldn't seem to find a solution. Thank you for any form of feedback that there may be.)

JavaScript Class Constructor and DOM (Updated)

I am new to programming, and I don't quite grasp the idea of utilizing class constructor in real life. For instance, let's just say I am trying to create a DOM event handler so I can take user input and push it into CreateTodoList.todos array.
class CreateTodoList {
constructor(list) {
this.todoList = list;
this.todos = [];
}
Then let's just assume that I have built addTodo() function which takes text parameter where an user enters her/his todo.
addTodo(text) {
this.todos.push(text);
this.todoList.appendChild(CreateTodoList.addtoList(text));
}
Here, addtoList creates DOM element that takes value of the user input.
This addTodo function, then pushes the text parameter into the array I made in constructor, while also calling addtoList that makes the DOM element.
Now, let's say I click on "add" button where it takes user input value.
I will build an event handler that responds to click which will add user input to the todoList.
CreateTodoList.eventHandler('click', (e) => {
let userText.todos = document.querySelector(#userInput).value;
addTodo(userText);
})
I am trying to build an eventHandler here, so I can add user input to todoList, and have implemented this several times, but had no luck but receiving reference error.
Below is my full code.
/** #format */
const add = document.querySelector('#btn_add');
let addInput = document.querySelector('#add');
const form = document.querySelector('#form');
class CreateTodoList {
constructor(list) {
this.todoList = list;
this.todos = [];
}
addtoList(text) {
let checkboxEl = document.createElement('span');
checkboxEl.classList.add('round');
let checkboxEl2 = document.createElement('input');
checkboxEl2.id = 'checkbox';
checkboxEl2.type = 'checkbox';
let checkboxEl3 = document.createElement('label');
checkboxEl3.htmlFor = 'checkbox';
checkboxEl.appendChild(checkboxEl2);
checkboxEl.appendChild(checkboxEl3);
let todoTextEl = document.createElement('input');
todoTextEl.value = text;
todoTextEl.disabled = true;
todoTextEl.classList.add('edit_input');
todoTextEl.id = 'edit_input';
todoTextEl.type = 'text';
todoTextEl.name = 'edit_input';
let todoTextEl2 = document.createElement('label');
todoTextEl2.htmlFor = 'edit_input';
let editEl = document.createElement('i');
editEl.classList.add('far');
editEl.classList.add('fa-edit');
let deleteEl = document.createElement('i');
deleteEl.classList.add('far');
deleteEl.classList.add('fa-trash-alt');
let dateEl = document.createElement('small');
dateEl.textContent = timeago.format(new Date());
let liEl = document.createElement('li');
liEl.appendChild(checkboxEl);
liEl.appendChild(todoTextEl);
liEl.appendChild(todoTextEl2);
liEl.appendChild(editEl);
liEl.appendChild(deleteEl);
liEl.appendChild(dateEl);
let list = document.querySelector('ul');
list.appendChild(li);
return liEl;
}
removeFromList(text) {
let list = document.querySelector('ul');
let childs = Array.from(list.childNodes);
let removable = child.find((i) => i.innerText === text);
return item;
}
//todos 배열(todo 데이터에) text를 추가한다.
//todoList 에 liEL(리스트 엘레먼트) 를 append 한다.
addTodo(text) {
this.todos.push(text);
this.todoList.appendChild(CreateTodoList.addtoList(text));
}
removeTodo(text) {
let removed = this.todos.filter((el) => el !== text);
todo.todoList.removeChild(CreateTodoList.removeFromList(text));
this.todos = removed;
}
get getList() {
return this.todos;
}
}
class Handlers {}

Array containing objects is not updating

I am new in programming. I am trying to update cart items. On instance of click "OK" in modal, the One_item object is updated. Then this object is passed on to Cart_Item array, which contains the total items.
I tried to write the logic in Listval() function in the Menu component. The One_Item is updated properly.
But the if condition at the bottom of the Listval(), is adding , but not updating. Also the first click gives an empty object.
Please see the sandbox:
https://codesandbox.io/s/hardcore-stallman-98o58
Relevant function to look into:
Listval() {
let ll = "$" + this.state.listvalue.replace(/[^0-9]/g, "");
let ll2 = this.state.listvalue.replace(/\d+/g, "");
let ll3 = ll2.replace(/\$/g, "");
let ll4 = ll.replace(/\$/g, "");
let ll5 = this.state.Select_Quantity;
let ll6 = parseFloat(ll4) * ll5;
let ll7 = this.state.Total_Item || [];
ll7.push(ll3);
ll7 = [...new Set(ll7)];
this.setState(
{
Select_Price: ll,
Select_Item: ll3,
Select_Item_TotalPrice: ll6,
Total_Item: ll7
},
() => {
// CHANGE: Use callback function to send data to the parent component
this.props.updateTotalItems(this.state.Total_Item.length);
}
);
// append new object This is where problem starts, the new object pushes at second click
if (this.state.Item !== this.state.Select_Item) {
let xx = {
Price: ll,
Item: ll3,
Quantity: this.state.Select_Quantity,
Total_Item_Price: ll6
};
// const Cart_Item = Object.assign(xx, this.state.Cart_Item);
let yy = this.state.Cart_Item || [];
yy.push(xx);
this.setState({ Cart_Item: yy });
}
//else try to update object based on property value
// This is not working at all. it keeps on adding objects instead of updating
else {
for (var i in this.state.Cart_Item) {
if (this.state.Cart_Item[i].value === this.state.Select_Item) {
this.state.Cart_Item[i].Price = ll;
this.state.Cart_Item[i].Item = ll3;
this.state.Cart_Item[i].Quantity = this.state.Select_Quantity;
this.state.Cart_Item[i].Total_Item_Price = ll6;
// }
break; //Stop this loop, we found it!
}
}
// i tried below logic as well but it didnt work
// this.setState({
// Cart_Item:this.state.Cart_Item.filter(v => v.this.state.Select_Item.includes(this.state.Item))
// .concat([ xx ])
// });
}
console.log(this.state.Cart_Item);
}

How would I use local storage for a to do list?

I am being asked to have a to do list and save each task (that the user supplies as well as original) through local storage. My teacher did a very simple demo on something completely different and I spent a few hours trying to figure it out. When I looked at the solution, I honestly cannot figure it out. It looks really complicated, and I don't even know where to start. If anyone can give me any hints, that would be awesome!
My code:
let ul = document.querySelector('ul');
let newItem = document.querySelector('input[type=text]');
let checkbox = document.createElement('input');
checkbox.setAttribute('type', 'checkbox');
function output() {
let newTodo = document.createElement('li');
newTodo.innerText = newItem.value;
newTodo.classList.add('todo');
let ulAppend = ul.append(newTodo);
ul.append(newTodo);
let checkboxAppend = newTodo.append(checkbox);
newTodo.append(checkbox);
newItem.value = '';
}
let button = document.querySelector('.btn');
button.addEventListener('click', output);
ul.addEventListener('click', function(e) {
if (e.target.tagName === 'LI') {
e.target.remove();
} else if (e.target.tagName === 'INPUT') {
e.target.parentElement.classList.toggle('finished');
}
});
My teacher's code/local storage solution:
const todoForm = document.getElementById("newTodoForm");
const todoList = document.getElementById("todoList");
// retrieve from localStorage
const savedTodos = JSON.parse(localStorage.getItem("todos")) || [];
for (let i = 0; i < savedTodos.length; i++) {
let newTodo = document.createElement("li");
newTodo.innerText = savedTodos[i].task;
newTodo.isCompleted = savedTodos[i].isCompleted ? true : false;
if (newTodo.isCompleted) {
newTodo.style.textDecoration = "line-through";
}
todoList.appendChild(newTodo);
}
todoForm.addEventListener("submit", function(event) {
event.preventDefault();
let newTodo = document.createElement("li");
let taskValue = document.getElementById("task").value;
newTodo.innerText = taskValue;
newTodo.isCompleted = false;
todoForm.reset();
todoList.appendChild(newTodo);
// save to localStorage
savedTodos.push({ task: newTodo.innerText, isCompleted: false });
localStorage.setItem("todos", JSON.stringify(savedTodos));
});
todoList.addEventListener("click", function(event) {
let clickedListItem = event.target;
if (!clickedListItem.isCompleted) {
clickedListItem.style.textDecoration = "line-through";
clickedListItem.isCompleted = true;
} else {
clickedListItem.style.textDecoration = "none";
clickedListItem.isCompleted = false;
}
// breaks for duplicates - another option is to have dynamic IDs
for (let i = 0; i < savedTodos.length; i++) {
if (savedTodos[i].task === clickedListItem.innerText) {
savedTodos[i].isCompleted = clickedListItem.isCompleted;
localStorage.setItem("todos", JSON.stringify(savedTodos));
}
}
});
Even though my code is more simpler (at least from what I can tell), it works exactly as his code does.
Local storage saves a JSON object to the user's computer. You should create an array of todos, append that array with every new todo, then set that item to local storage.
let ul = document.querySelector('ul');
const savedTodos = JSON.parse(localStorage.getItem("todos")) || []; // Retrieves local storage todo OR creates empty array if none exist
let newItem = document.querySelector('input[type=text]');
let checkbox = document.createElement('input');
checkbox.setAttribute('type', 'checkbox');
function output() {
let newTodo = document.createElement('li');
newTodo.innerText = newItem.value;
newTodo.classList.add('todo');
ul.append(newTodo);
newTodo.append(checkbox);
savedTodos.push({task: newItem.value, isCompleted: false}); // Appends the new todo to array
localStorage.setItem("todos", JSON.stringify(savedTodos)); //Converts object to string and stores in local storage
newItem.value = '';
}
I've annotated the solution you posted with some comments to help you step through it.
// Retrieve elements and store them in variables
const todoForm = document.getElementById("newTodoForm");
const todoList = document.getElementById("todoList");
// Get data stored in localStorage under the key "todos".
// The data type will be a string (local storage can only store strings).
// JSON is a global object that contains methods for working with data represented as strings.
// The `||` syntax is an OR operator and is used here to set an empty array as a fallback in case `localStorage` is empty
const savedTodos = JSON.parse(localStorage.getItem("todos")) || [];
// Create a loop the same length as the list of todos
for (let i = 0; i < savedTodos.length; i++) {
// Create an <li> element in memory (does not appear in the document yet)
let newTodo = document.createElement("li");
// Set the inner text of that new li with the contents from local storage.
// The savedTodos[i] is accessing data in the localStorage array.
// The [i] is a different number each loop.
// The `.task` is accessing 'task' property on the object in the array.
newTodo.innerText = savedTodos[i].task;
// Create a new property on the element called `isCompleted` and assign a boolean value.
// This is only accessible in code and will not show up when appending to the DOM.
newTodo.isCompleted = savedTodos[i].isCompleted ? true : false;
// Check the value we just set.
if (newTodo.isCompleted) {
// Create a style for the element if it is done (strike it out)
newTodo.style.textDecoration = "line-through";
}
// Actually append the new element to the document (this will make it visible)
todoList.appendChild(newTodo);
}
// `addEventListener` is a function that registers some actions to take when an event occurs.
// The following tells the browser - whenever a form is submitted, run this function.
todoForm.addEventListener("submit", function(event) {
// Don't try to send the form data to a server. Stops page reloading.
event.preventDefault();
// Create a <li> element in memory (not yet visible in the document)
let newTodo = document.createElement("li");
// Find element in the document (probably a input element?) and access the text value.
let taskValue = document.getElementById("task").value;
// Set the text of the <li>
newTodo.innerText = taskValue;
// Set a property on the <li> call `isCompleted`
newTodo.isCompleted = false;
// Empty out all the input fields in the form
todoForm.reset();
// Make the new <li> visible in the document by attaching it to the list
todoList.appendChild(newTodo);
// `push` adds a new element to the `savedTodos` array. In this case, an object with 2 properties.
savedTodos.push({ task: newTodo.innerText, isCompleted: false });
// Overwrite the `todos` key in local storage with the updated array.
// Use the JSON global object to turn an array into a string version of the data
// eg [1,2,3] becomes "[1,2,3]"
localStorage.setItem("todos", JSON.stringify(savedTodos));
});
// This tells the browser - whenever the todoList is clicked, run this function.
// The browser will call the your function with an object that has data about the event.
todoList.addEventListener("click", function(event) {
// the `target` of the event is the element that was clicked.
let clickedListItem = event.target;
// If that element has a property called `isCompleted` set to true
if (!clickedListItem.isCompleted) {
// update the styles and toggle the `isCompleted` property.
clickedListItem.style.textDecoration = "line-through";
clickedListItem.isCompleted = true;
} else {
clickedListItem.style.textDecoration = "none";
clickedListItem.isCompleted = false;
}
// The code above changes the documents version of the data (the elements themselves)
// This loop ensures that the array of todos data is kept in sync with the document
// Loop over the array
for (let i = 0; i < savedTodos.length; i++) {
// if the item in the array has the same text as the item just clicked...
if (savedTodos[i].task === clickedListItem.innerText) {
// toggle the completed state
savedTodos[i].isCompleted = clickedListItem.isCompleted;
// Update the localStorage with the new todos array.
localStorage.setItem("todos", JSON.stringify(savedTodos));
}
}
});
Keep in mind, there are 2 sources of state in your todo list. One is how the document looks, and the other is the array of todos data. Lots of challenges come from making sure these 2 stay in sync.
If somehow the document showed one of the list items as crossed out, but your array of data shows that all the todos are not completed, which version is correct? There is no right answer here, but state management will be something you might consider when designing apps in the future. Redux is a good js library with a well understood pattern that helps solve this problem. Hope this last comment doesn't confuse too much. Best of luck!
The important part is in (de)serializing the data. That means:
reading from localStorage (JSON.parse(localStorage.getItem("todos")) || [])
We add the default [] because if the todos key does not exist, we will get null and we expect a list
saving to localStorage (localStorage.setItem("todos", JSON.stringify(savedTodos)))
We need JSON.parse and its complementary operation JSON.stringify to parse and save strings because localStorage can store only strings.
In your case you need to read the data from localStorage and render the initial list. To save it to localStorage, again, you have to serialize the data. See the below snippets (link to working JSFIDDLE, because the below example does not work in the StackOverflow sandbox environment):
let ul = document.querySelector('ul');
let newItem = document.querySelector('input[type=text]');
const Store = {
serialize () {
return [].slice.call(document.querySelectorAll("li")).map(c => {
return {
text: c.textContent,
finished: c.querySelector("input").checked
}
})
},
get () {
return JSON.parse(localStorage.getItem("todos")) || []
},
save () {
return localStorage.setItem("todos", JSON.stringify(Store.serialize()))
}
}
const firstItems = Store.get()
firstItems.forEach(it => {
output(it.text, it.finished)
})
function output(v, finished) {
let newTodo = document.createElement('li');
newTodo.innerText = v || newItem.value;
newTodo.classList.add('todo');
let ulAppend = ul.append(newTodo);
ul.append(newTodo);
// Create a checkbox for each item
let checkbox = document.createElement('input');
if (finished) {
checkbox.checked = true
}
checkbox.setAttribute('type', 'checkbox');
let checkboxAppend = newTodo.append(checkbox);
newTodo.append(checkbox);
newItem.value = '';
}
let button = document.querySelector('.btn');
button.addEventListener('click', () => {
output()
Store.save()
});
ul.addEventListener('click', function(e) {
if (e.target.tagName === 'LI') {
e.target.remove();
} else if (e.target.tagName === 'INPUT') {
e.target.parentElement.classList.toggle('finished');
}
// Update the value in localStorage when you delete or add a new item
Store.save()
});
<ul></ul>
<input type="text" /> <button class="btn">Submit</button>
I have added the Store variable to simplify the way you get and set the data in localStorage.
The serialize method will read the TODOs from the list. document.querySelectorAll("li") returns a NodeList, but by doing [].slice.call(...) we convert it to an Array.

Remove one item from an array when clicked by only js

I am new to JavaScript. I have a small code that creates list from input and then adds it to an array. I am able to remove one item from the DOM when the item is clicked, but I couldn't remove it from the array.
I tried to use array.splice(item, 1)
lists.addEventListener("click", function (e) {
e.target.closest("li").remove();
userInputArr.splice(item, 1);});
But it removes the entire array sometime, and sometime removes the last item. when I console log the code, it looks like I clicked 3 or 4 times on the list even though I just clicked once. I have no idea what's wrong. this is the entire code:
const lists = document.querySelector(".lists");
const userInput = document.querySelector(".add-note");
const addBtn = document.querySelector(".add-btn");
const item = document.querySelectorAll(".list");
userInputArr = [];
function addNote() {
if (userInput.value < 1) {
return;
}
lists.insertAdjacentHTML(
"afterbegin",
`<li class='list'>${userInput.value}</li>`
);
userInputArr.push(lists);
lists.addEventListener("click", function (e) {
e.target.closest("li").remove();
userInputArr.splice(item, 1);
});
userInput.value = "";
}
addBtn.addEventListener("click", function () {
addNote();
});
Code is totally meaningless
1)
userInputArr.push(lists)
why you push the same element all the time? As lists refers to the first and the only element with class 'lists'?
2)
userInputArr.splice(item, 1)
please watch carefully what splice does? The first argument is number, but you pass a collection of elements with class 'list'. But i camn not even suggest which element should be removed as it contains the same element as i mentioned in first point
3) You do not need this array at all
So right approach is something like this
const lists = document.querySelector(".lists");
// just once create listener, no need to do it each time
lists.addEventListener("click", function (e) {
// if you want to remove clicked item then
if (e.target.tagName === 'LI') e.target.remove();
// but if you want to remove the first one then uncomment line
// if (this.children[0]) this.children[0].remove()
});
const userInput = document.querySelector(".add-note");
const addBtn = document.querySelector(".add-btn");
///////////////////////////////////////////////////
// item is meaninglee here, so delete this line
// const item = document.querySelectorAll(".list");
//////////////////////
// array is useless too, delete this line
// userInputArr = [];
function addNote() {
// check if it is number
if (isNaN(userInput.value) || Number(userInput.value < 1)) {
return;
}
lists.insertAdjacentHTML(
"afterbegin",
`<li class='list'>${userInput.value}</li>`
);
userInput.value = "";
}
addBtn.addEventListener("click", function () {
addNote();
});
const items = (() => {
const _items = {};
let key = 0;
return {
put(value) {
_items[key++] = value;
console.log("Added", this.all());
return key - 1;
},
remove(key) {
delete _items[key++];
console.log("Removed", this.all());
},
all(asArray = true) {
return asArray ? Object.values(_items) : { ..._items
};
}
}
})();
const inputEl = document.querySelector(".input");
const itemsEl = document.querySelector(".items");
const addBtn = document.querySelector(".btn-add");
addBtn.addEventListener("click", () => {
const value = inputEl.value.trim();
if (!value.length) return;
const key = items.put(value);
const li = document.createElement("li");
li.textContent = value;
li.dataset.key = key;
itemsEl.append(li);
inputEl.value = "";
});
itemsEl.addEventListener("click", (e) => {
const li = e.target.closest("li");
items.remove(li.dataset.key);
li.remove();
});
<input type="text" class="input">
<button class="btn-add">Add</button>
<ul class="items"></ul>
Run code & View in full screen.
use shift() userInputArr.shift()
you are also getting double clicks because your addNote() function contains an event listener lists.addEventListener and it's executed by another event listner addBtn.addEventListener you should probably move
lists.addEventListener out of the addNote function

Categories

Resources