How can i delete a specific li list on click? - javascript

const list = document.getElementById('list')
const addtodo = document.getElementById('addtodo')
//const items = document.querySelector('.item')
const deleteItem = document.querySelector('.delete')
addtodo.addEventListener('keypress', submitTodo)
function submitTodo(event) {
if (event.keyCode == 13) {
event.preventDefault()
let value = addtodo.value
let li = document.createElement('li')
li.innerHTML = `
<img class="unchecked" src="icon/unchecked.svg" />
${value}
<img class="delete" src="icon/icons8-multiply-26.png" /> `
list.appendChild(li)
}
}
deleteItem.addEventListener('click', items)
function items(item) {
if (item.target.classList.contains('delete')) {
item.target.parentElement.remove()
}
}
The code above only allows me to delete one item and its the first one on the list
I try to solve it on my own but couldn't any idea whats wrong

When deleteItem.addEventListener('click', items) is ran, it only attaches the eventListener to the elements currently on the DOM - the ones you create dynamically will not have this eventListener
You can use 'event delegation' instead to listen for clicks, and filter theses clicks based on if the click was coming from the correct element
You can read more about event delegation from davidwalsh's blog and this StackOverflow answer
document.addEventListener('click', function(e) => {
if(e.target && e.target.classList.includes('delete')){
e.target.parentElement.remove()
}
});
You could also make use of the elements onclick attribute, and pass this in the parameter of the function call - this way you can access the HTML Element directly from the parameter; this also avoids having to have an eventListener, or using an if to check if it's the correct class / ID
// Add the function to the onclick attribute of the img
<img class="delete" onclick="deleteItem(this)" src="demo.png" />
// in this function, 'item' refers to the DOM Element that was clicked
function deleteItem (item) {
item.parentElement.remove();
}

This code will allow you to remove the first element on ul .
let list = document.getElementById("list"); // ul element
let remove = document.getElementById("remove"); // remove button
// on double click event
remove.onclick = () => {
// remove the first child from the list
list.removeChild(list.firstChild);
}
<ul id="list">
<li>One</li>
<li>Two</li>
<li>three</li>
</ul>
<input type="button" id="remove" value="Remove First"></input>

Related

How do I add a delete button next to my task list?

This is what i have right now, what code do i add to make buttons next to my tasks, so with every new task there must come a remove button as well
document.getElementById('submit').addEventListener('click', withClick);
function withClick(e) {
const li = document.createElement('li')
document.getElementById('listid').appendChild(li);
li.appendChild(document.createTextNode(document.getElementById("text-area").value))
li.id = 'list'
li.className = 'collection-item'
const button = document.createElement('button')
document.getElementById('list').appendChild(button);
button.appendChild(document.createTextNode('x'))
button.className = "button"
}
<ul id="listid">
</ul>
<input id="text-area">
<button id="submit">submit</button>
This is what it looks like in browser
id needs to be unique in HTML.
Currently every <li> element you create has id="list". So when you do this:
document.getElementById('list')
Which one do you expect it to find and why? The behavior is likely undefined, but what you're observing is that it finds the first one with that id and then stops searching. Because why wouldn't it? Once it finds the element with the target id, as far as the browser is concerned it has found the one target element you're looking for.
Instead of fetching the element by its id, you already have a reference to it in the li variable. Just use that:
document.getElementById('submit').addEventListener('click', withClick);
function withClick(e) {
const li = document.createElement('li')
document.getElementById('listid').appendChild(li);
li.appendChild(document.createTextNode(document.getElementById("text-area").value))
li.className = 'collection-item'
const button = document.createElement('button')
li.appendChild(button); // <---- here
button.appendChild(document.createTextNode('x'))
button.className = "button"
}
<ul id="listid">
</ul>
<input id="text-area">
<button id="submit">submit</button>

Getting the whole content of a clicked <li> element

This is my HTML line:
<li onclick="return open_create_event_screen();">10</li>
I want to get the content of this < li > element (which is '10') through the JavaScript function (open_create_event_screen()) that opens once the < li > element is clicked.
Is it possible to do so?
Old way, where we put inline events into our HTML. The key is to pass this into the function, which is a reference to the element that was acted upon, you could also pass event, and determine the clicked element from the target property (two different approaches).
const open_create_event_screen = (obj) => {
console.log("opening create event screen");
console.log(obj.innerText);
}
<li onclick="open_create_event_screen(this);">10</li>
Here's a more modern approach, where our html is cleaner, and we do the work of assigning the event handlers in javascript.
const open_create_event_screen = (obj) => {
console.log("opening create event screen");
console.log(obj.innerText);
}
const lis = document.querySelectorAll(".eventThing>li");
lis.forEach(li =>
li.addEventListener("click", () => open_create_event_screen(li))
);
<ul class="eventThing">
<li>10</li>
<li>20</li>
</ul>

How to assign dynamic children a click event listener?

I have a parent container with a number of elements, it's not a well defined number of elements, it's generated by using an API once the user starts typing something in an input field. Also these elements are parents to other elements. (I'll give an example below)
The idea is that once the user clicks that element, I want to display an overlay with more information about that specific element. Sounds good, but the things I've tried didn't work so far.
I tried to add an event listener onto the container. Consider this basic HTML template.
<ul>
<li><span>Item 1</span><span>X</span></li>
<li><span>Item 2</span><span>X</span></li>
<li><span>Item 3</span><span>X</span></li>
<li><span>Item 4</span><span>X</span></li>
</ul>
<form>
<input type="text" id="test">
</form>
So here we have an UL which is the parent element and LI are its children. However, LI are also parents to the span tags that are supposedly showing some vital information so I cannot remove those tags.
The input field is here just to add something dyamically, to mimik the way my API works.
So like I said, I have tried to add an event listener on the UL parent >>
const items = ul.querySelectorAll('li');
items.forEach(item => item.addEventListener('click', function(e) {
console.log(this);
}));
});
});
Then I tried to add an event listener to each of the items, but instead of logging one item at a time as I click them, it's logging one, two, three and so forth.
I feel that I'm missing something here and I don't know what it is. Can you guys help me out?
Later edit: I found this solution but it doesn't seem very elegant to me and it's prone to bugs if I change stuff later on (like add more children etc).
ul.addEventListener('click', e => {
const items = ul.querySelectorAll('li');
if(e.target.tagName === 'LI' || e.target.parentElement.tagName === 'LI') {
if(e.target.tagName === 'LI') {
e.target.remove();
} else if(e.target.parentElement.tagName === 'LI') {
e.target.parentElement.remove();
}
}
});
You can use the function Element.closest() to find a parent element.
const ul = document.querySelector('ul');
ul.addEventListener('click', e => {
let li = e.target.closest('LI');
li.remove();
});
document.forms.newitem.addEventListener('submit', e => {
e.preventDefault();
let newitem = document.createElement('LI');
newitem.innerText = e.target.test.value;
ul.appendChild(newitem);
});
<ul>
<li><span>Item 1</span><span>X</span></li>
<li><span>Item 2</span><span>X</span></li>
<li><span>Item 3</span><span><em>X</em></span></li>
<li>Item 4 X</li>
</ul>
<form name="newitem">
<input type="text" name="test">
</form>
The reason that you got all line events every time that you've clicked in a line, is that you are add a event click in ul element and you just need it in the li element
A way very similar that you'd like:
let ul = document.querySelector("ul");
const items = ul.querySelectorAll("li");
items.forEach((item) =>
item.addEventListener("click", function (e) {
let getTargetRow = e.target.parentElement;
if (getTargetRow.nodeName === "LI"){
console.log("the line removed:",getTargetRow.textContent);
getTargetRow.remove();
}
})
);
<ul>
<li><span>Item 1</span><span>X</span></li>
<li><span>Item 2</span><span>X</span></li>
<li><span>Item 3</span><span>X</span></li>
<li><span>Item 4</span><span>X</span></li>
</ul>
<form>
<input type="text" id="test" />
</form>

Adding a remove item function that is inserted with innerHTML?

I have an add to cart functionality and I am trying to create a remove from cart button. The problem I am having is getting the remove button to be unique to each cart item. It is currently functioning very funny, clicking the first item in the cart deletes all of the other items, and if I select a cart item other than the first one it deletes a different one. How can I make this work? I want to remove the entire LI element upon click.
let gridItems = document.querySelectorAll(".grid-item");
let ul = document.querySelector(".footer-container");
let num = 0;
gridItems.forEach((item) => {
const button = item.querySelector(".add-btn");
button.addEventListener("click", () => {
ul.insertAdjacentHTML(
"beforeend",
`<li class="footer-items">
<button class="remove-item">X</button>
<div class="side-by-side">
${
item.querySelector(".title").textContent
} <img class="cart-image" src="${item
.querySelector(".bike-image")
.getAttribute("src")}"/></div> <span class="cart-price">${
item.querySelector(".item-price").textContent
}</span> </li>`
);
//My attempt at removing each item
document
.querySelector(".remove-item")
.addEventListener("click", function () {
document.querySelector(".footer-items").remove();
});
});
});
I was able to figure out a solution to the problem by creating a for each loop and targeting the parentNode selector for each item and removing it.
document.querySelectorAll(".remove-item").forEach((item) => {
item.addEventListener("click", function () {
item.parentNode.remove();
});
});

Adding event listeners to <li> that are created using javascript

I am quite new to manipulating elements in the DOM in JS so I am creating a simple to do list to get more comfortable and where I can add items using the input and remove items by clicking on the list item.
ALthough this may not be best practice and limitting I am just wanting to use create and remove elements rather than using objects or classes until I get more familar, also using plain/vanilla js so please keep this in mind when answering.
I am trying to add a click event which removes the <li> when the <li> is clicked.
My logic is...
When the page is loaded I can't just run a for loop over all of the <li>s and add event handlers as all of the <li>'s do not exist yet.
So my attempted solution is when the addTaskButton event is triggered, we get all of the <li> that are on the page at the time of the event, we loop through all of them and add an eventlistener to <li>'s that are waiting to be removed when clicked.
This doesn't seem to work and may be overly complicated.
Can someone please explan to me very simply like I'm 5 why this doesn't work or what a better way to do this would be?
Thank you in advance
HTML
<ul id="taskList">
<li>example</li>
</ul>
<input type="text" id="addTaskInput">
<button id="addTaskButton">Add Task</button>
JavaScript
const taskList = document.querySelector("#taskList");
const addTaskInput = document.querySelector("#addTaskInput");
const addTaskButton = document.querySelector("#addTaskButton");
let taskItem = document.querySelectorAll("li");
addTaskButton.addEventListener("click", () => {
let taskItem = document.createElement("li");
taskItem.textContent = addTaskInput.value;
for (let i = 0; i < taskItem.length; i++) {
taskItem[i].addEventListener("click", () => {
let taskItem = document.querySelectorAll("li");
taskList.removeChild(taskItem[i]);
});
}
taskList.appendChild(taskItem);
addTaskInput.value = " ";
});
Here is code i created for your requirement, this implement jQuery $(document).on mechanism in vanilla javascript, now where ever you create an li inside the document, on clicking that li it will be removed.
Explaination
What it does is on clicking the document it checks on which element is clicked (e.target is the clicked element, e is is the click event on document), then checks if the clicked item is an li tag (e.target.tagName will tell us the tag name if the item clicked), so if it is an li just remove it;
const taskList = document.querySelector("#taskList");
const addTaskInput = document.querySelector("#addTaskInput");
const addTaskButton = document.querySelector("#addTaskButton");
addTaskButton.addEventListener("click", () => {
let taskItem = document.createElement("li");
taskItem.textContent = addTaskInput.value;
taskList.appendChild(taskItem);
addTaskInput.value = " ";
});
document.onclick = function(e)
{
if(e.target.tagName == 'LI'){
e.target.remove();
}
}
<ul id="taskList">
<li>example</li>
</ul>
<input type="text" id="addTaskInput">
<button id="addTaskButton">Add Task</button>
Update your for loop like so:
for (let i = 0; i < taskItems.length; i++) {
taskItems[i].addEventListener("click", () =>
taskList.removeChild(taskItems[i]);
});
}
Also your initial taskItem variable should be taskItems and is reflected in the for loop above.
taskList.addEventListener("click", (event) => {
event.target.remove();
});
When the specified event occurs the event object is returned.
The event object has several properties, one of them being target which is the element which is the element which the event occured on. event.target is returned to us and we are applying the remove() method to event.target
because of event "bubbling" or "Event Propagation", we can attach the event handler to an ancestor. It's best to attach the event listener to the closest ancestor element that is always going to be in the DOM (won't be removed).
When an event is triggered-in this case the "click" event. All decending elements will be removed - which in our case as there are only <li>'s this would be fine. But we should be more specific as in a different case we could be attaching this event handler to a div which has several different elements.
To do this we add an if condition to check that the tagName is an <li>
if (event.target.tagName == "LI")
note that the element must be calpitalised
Solution is as follows
taskList.addEventListener("click", (event) => {
if(event.target.tagName == "LI"){
event.target.remove();
}});
Further reading:
Event object and its properties:
https://developer.mozilla.org/en-US/docs/Web/API/Event
Event Bubbling:
https://developer.mozilla.org/en-US/docs/Web/API/Event/bubbles
tagName:
https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName

Categories