Is there a way to incorporate a deletion feature within a list of items using JavaScript?

When adding a new item, I want to include a delete button next to it so I can easily remove the item by clicking on the button. However, I am having trouble figuring out how to implement this functionality using JavaScript.

You can view my code snippet here: https://codepen.io/otaylor3/pen/MWaeYPL

// Sample Code Goes Here
// CSS Styling Goes Here
<!DOCTYPE html>
<html>
<head>
<title>Sample HTML Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a sample paragraph.</p>

<script type="text/javascript" src="script.js"></script>
</body>
</html>

Answer №1

One effective approach is to attach a single event listener to the ul element and then check if the target is the delete button. This method proves to be more efficient compared to adding multiple event listeners separately.

Read more here

ul.addEventListener("click", function(e) {
  var target = e.target;
  if (target.classList.contains("delete")) {
    target.parentNode.remove();
  }
});

// Define variables for my shopping list 
var input = document.getElementById("userinput");
var button = document.getElementById("enter");
var ul = document.querySelector("ul");
var list = document.getElementsByTagName("li");
var trash = document.getElementsByClassName("delete");
var btndelete = document.getElementById("trash");

// Add event listener on 'ul' to handle click events efficiently
ul.addEventListener("click", function(e) {
  var target = e.target;
  if (target.classList.contains("delete")) {
    target.parentNode.remove();
  }
});

// Function to toggle strike-through effect
function strikeout() {
  this.classList.toggle("done");
}

// Check the length of input value
function inputlength() {
  return input.value.length;
}

// Collect data from input field and add as a new list item
function addli() {
  var li = document.createElement("li");
  var btn = document.createElement("button");
  li.appendChild(document.createTextNode(input.value));
  ul.appendChild(li);
  input.value = "";
}

// Method to trigger addition of a new list item upon click
function addListAfterClick() {
  if (inputlength() > 0) {
    addli();
  }
}

// Method to trigger addition of a new list item upon key press
function addListKeyPress(event) {
  if (input.length() > 0 && event.which === 13) {
    addli();
  }
}

// Event listener for keypress to add new list item
input.addEventListener("keypress", addListKeyPress);

// Event listener for click to add new list item
button.addEventListener("click", addListAfterClick);
body {
  background-image: url("easy.jpg");
}

.coolTitle {
  text-align: center;
  font-family: 'Oswald', Helvetica, sans-serif;
  font-size: 80px;
  transform: skewY(-10deg);
  letter-spacing: 4px;
  word-spacing: -8px;
  color: tomato;
  text-shadow: -1px -1px 0 firebrick, -2px -2px 0 firebrick, -3px -3px 0 firebrick, -4px -4px 0 firebrick, -5px -5px 0 firebrick, -6px -6px 0 firebrick, -7px -7px 0 firebrick, -8px -8px 0 firebrick, -30px 20px 40px dimgrey
}

.done {
  text-decoration: line-through;
}

li {
  margin-top: 6px;
}
<!DOCTYPE html>
<html>

<head>
  <title>Shopping List</title>
  <link rel="stylesheet" type="text/css" href="list.css">
</head>

<body>
  <h1>Shopping List</h1>
  <h2 class="second"> Get it Done </h2>
  <input id="userinput" type="text" placeholder="enter items">
  <button id="enter">Enter</button>

  <ul id="bold">
    <li random="24">Eggs <button class="delete">delete</button></li>
    <li>Milk <button class="delete">delete</button></li>
    <li>Cereal<button class="delete">delete</button></li>
    <li>Chicken <button class="delete">delete</button></li>
    <li>Oreos <button class="delete">delete</button></li>
  </ul>

  <script type="text/javascript" src="list.js"></script>
</body>

</html>

Answer №2

To create a button element and attach an event listener to it, follow these steps:

// Define variables for the shopping list 
var input = document.getElementById("userinput");
var button = document.getElementById("enter");
var ul = document.querySelector("ul");
var list = document.getElementsByTagName("li");
var trash = document.getElementsByClassName("delete");
var btndelete = document.getElementById("trash");

// Add event listeners to remove items with the delete button
Array.prototype.slice.call(trash).forEach(function(item) {
  item.addEventListener("click", function(e) {
    e.target.parentNode.remove();
  });
});

// Add strikeout effect when clicking on list items
for (var i = 0; i < list.length; i++) {
  list[i].addEventListener("click", strikeout);
}

// Toggle between classes to add or remove strikeout style
function strikeout() {
  this.classList.toggle("done");
}

// Check the length of the entered string
function inputlength() {
  return input.value.length;
}

// Collect data from the input and create a new list item
function addli() {
  var li = document.createElement("li");
  var btn = document.createElement("button");
  btn.className = "delete";
  btn.innerHTML = "delete";
  btn.addEventListener("click", function(e) {
    e.target.parentNode.remove();
  });
  li.addEventListener("click", strikeout);
  li.innerHTML = input.value + " ";
  li.appendChild(btn);
  ul.appendChild(li);
  input.value = "";
}

// Add a new list item after clicking the button
function addListAfterClick() {
  if (inputlength() > 0) {
    addli();
  }
}

// Add a new list item when pressing Enter key
function addListKeyPress(event) {
  if (inputlength() > 0 && event.which === 13) {
    addli();
  }
}

// Listen for keypress events on the input field
input.addEventListener("keypress", addListKeyPress);

// Listen for click events on the button to add a new list item
button.addEventListener("click", addListAfterClick);
.coolTitle {
  text-align: center;
  font-family: 'Oswald', Helvetica, sans-serif;
  font-size: 80px;
  transform: skewY(-10deg);
  letter-spacing: 4px;
  word-spacing: -8px;
  color: tomato;
  text-shadow: -1px -1px 0 firebrick, -2px -2px 0 firebrick, -3px -3px 0 firebrick, -4px -4px 0 firebrick, -5px -5px 0 firebrick, -6px -6px 0 firebrick, -7px -7px 0 firebrick, -8px -8px 0 firebrick, -30px 20px 40px dimgrey
}

.done {
  text-decoration: line-through;
}
<h1>Shopping List</h1>
<h2 class="second"> Get it Done </h2>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>

<ul id="bold">
  <li random="24">Eggs <button class="delete">delete</button></li>
  <li>Milk <button class="delete">delete</button></li>
  <li>Cereal <button class="delete">delete</button></li>
  <li>Chicken <button class="delete">delete</button></li>
  <li>Oreos <button class="delete">delete</button></li>
</ul>

Consider utilizing the click event of the ul element instead of attaching multiple event handlers to each li element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing conditional color parameter using Vuetify on an element

In my Vuetify project, I'm utilizing the built-in color parameter and predefined colors. My goal is to dynamically change the component's color based on the data it receives. For example, if complete: true, then the color should be green. Here&a ...

Animating SVG elements with the rotation property in SVG.js

Currently, I am utilizing Javascript, Jquery, SVG, and SVG.js in my project. My goal is to rotate a circle around its origin while it's animating. The issue arises when the animation keeps restarting abruptly, causing a jittery motion. Here is the ini ...

Struggling to find the right alignment for my Bootstrap card design

I'm attempting to center a card in the middle of the screen. While I was able to horizontally center it using mx-auto, I'm facing difficulties with vertical centering. I tried using mt-3 to add margin-top to the card, but it only gives me about ...

Discover the best practices for integrating media queries using Radium within Material UI components

Having trouble applying a breakpoint to the Material UI component, Raised button. I have managed to make it work for regular divs, but not for the Material UI component. I attempted wrapping the button inside Radium import RaisedButton from 'materia ...

What is the best way to customize the MenuProps of Material UI Select component using createTheme?

I'm trying to update the dropdown menu style of my Material UI Select component using createTheme, but I'm having trouble getting it to work. https://i.sstatic.net/zpVjW.png Here is the code I have so far. Can you spot what might be causing the ...

Can't access innerText in Firefox

This is the code snippet I'm having trouble with: <div id="code">My program<br />It is here!</div> <script type="text/javascript"> var program=document.getElementById('code'); ShowLMCButton(program.innerText); </s ...

Unlinking checkbox click event from row in Angular Material table

I am seeking to remove the ability for row selection in my table rows so that clicking anywhere within the row does not check the checkbox. I want the checkbox to only be checked when the box itself is clicked, allowing me to later add expandable rows when ...

Could anyone assist me in resolving the error stating, "The 'Argument `where` of type UserWhereUniqueInput needs at least one of `id` arguments"?

Upon investigating, I inserted this console log to determine what data is being received: { username: 'aa', gender: 'Feminino', cargo: '2', email: 'a', password: 'a' } Lately, I've been facing this err ...

dojo.xhrGet evaluating script tags

I have a piece of code that is similar to the following: var targetElem = dojo.byId('xyz'); var xhrArgs = { url: 'Welcome.do?call=JS', preventCache: true, load: function(data){ targetElem.innerHTML = data; dojo.parser.par ...

Challenges with parsing JSON using jQuery

I am attempting to retrieve data from a page that returns JSON in order to store it in an array. The current code is functional, but I am encountering difficulties when trying to pass the variable (which should contain the content) into the jQuery.parseJSO ...

Experimenting with a sample post on a minimalist Node.js application using Mocha and Superagent

I trust you are having a splendid day. Currently, I am focusing on enhancing my TDD skills in Node.js. To practice, I have developed a minimalistic application that handles basic GET and POST requests. The app simply displays a straightforward form to the ...

Why do the fontawesome icons fail to appear in my SVG file?

I've encountered a peculiar issue where icons (from fontawesome) are not appearing in my svg. They have always displayed correctly on my personal computer, so for a while I didn't realize that others were having trouble seeing them. For instance ...

Grayscale to color image slider using JQuery, HTML, and CSS

Seeking assistance from the talented individuals here. Currently in the process of constructing a website for a client, and one of the key components on the index page is an image slider/fader that showcases a series of images. The client has requested a u ...

CSS Styling Dropdown Menu for Internet Explorer 5 and Internet Explorer 11

I am encountering an issue with a select box that is coded as follows: <html:select property="list_data" size="12" style="width: 350px;" ondblclick="JavaScript:doOK()"> <html:optionsCollection property="list_data" label="codeAndNameLabel" val ...

Integrating a personalized dropdown feature into the Froala editor within an AngularJS environment

After searching for a JavaScript rich text editor that doesn't use frames and allows easy customization of the toolbar with custom dropdowns, I came across the Froala editor. It also offers AngularJS-friendly directives. Previously, I tried using Text ...

Utilize pandas.read_html to extract image alt text from web pages

Can you extract the text from the img alt attribute using pandas.read_html? The webpage I am trying to scrape has replaced some text with images, and the original text is now stored in the alt attribute of those images. For example: <td> <div>. ...

When provided with varied inputs, new Date() yields distinct values for various time zones

var date1 = "2015-03-29"; console.log(new Date(date1)); //Output:Sun Mar 29 2015 05:30:00 GMT+0530 (India Standard Time) var date2 = "1869-12-31"; console.log(new Date(date2)); //Output:Fri Dec 31 1869 05:53:20 GMT+0553 (India Standard ...

How to Access Data Attribute in React TypeScript on Click Event

Recently, I encountered a situation with my React component where I have a button with a click handler that utilizes the data-* attribute. In the past, with regular React, extracting the value from the data-* attribute was straightforward. However, as I am ...

Avoiding code execution by injections in Javascript/Jquery

Currently, I'm fetching JSON data for a .getJSON function in Jquery. To ensure the data's security, I am considering using .text (I believe this is the correct approach). The JSON has been successfully validated. Below is the script that I am cu ...

Is it possible to retrieve the index of a chosen v-select option within Vuetify?

Exploring Vuetify for the first time, I'm encountering an issue with obtaining the index of a selected option on the v-select component. My goal is to populate a text field based on the option that is clicked once I have the index. I am fetching an ...