deleting the selected list item with JavaScript

Currently, I am tackling a todo list project but facing a challenge in finding a vanilla Javascript solution to remove a list item once it has been clicked.

Adding user input as list items was relatively simple, but I have come to realize that this specific aspect of the task is more complex than I initially thought.

This project marks my introduction to JS. Each time a list item is added, a button element is included within the list item as a child.

The goal is for the user to click this button and have that particular list item removed from the unordered list.

Any suggestions on how to achieve this?

document.getElementById("add").addEventListener("click", function() {

  var taskinput = document.getElementById("task").value;

  if (taskinput) {

    var tasktext = document.createTextNode(taskinput);
    var list = document.createElement("li");
    list.appendChild(tasktext);
    var button = document.createElement("button");
    button.setAttribute("id", "completed");
    button.innerHTML = "completed";
    list.appendChild(button);
    document.getElementById("task-to-do").appendChild(list);
    document.getElementById("task").value = "";
  } else {
    alert("Please enter a task");
  }

  document.getElementById("completed").addEventListener("click", function() {

  })

})
ul {
  list-style: none;
}

ul li {
  position: relative;
  margin: auto;
  width: 80%;
  padding: 2% 2% 2% 2%;
  margin-bottom: 10px;
  color: white;
  border: 1px solid white;
  border-radius: 3px;
  background-color: #6363B6;
}

li button {
  display: block;
  width: auto;
  height: auto;
  padding: 1%;
  clear: both;
  float: right;
  background-color: #6363B6;
}
<div id="incomplete-tasks">
  <h4>INCOMPLETE TASKS</h4>
  <ul id="task-to-do">

  </ul>
</div>

Answer №1

If you want to easily identify the selected item from a button, you can utilize custom attributes. Data attributes come in handy for this purpose.

Here are the steps to follow:

  1. When creating a li element for a task, assign a unique id attribute using a counter, such as id = 1, 2, 3, etc.

    var list = document.createElement("li");
    list.setAttribute('id', (value-of-last-li-id) + 1);
    
  2. Similarly, when creating a button> element, give it a data attribute data-id with the same id value as the corresponding li element and a common class attribute value.

    var button = document.createElement("button");
    button.setAttribute('data-id', (value-of-last-li-id) + 1);
    button.setAttribute('class', 'delete-btn');
    
  3. Add an event listener for the click event on that button. This listener will retrieve the data-id of the button clicked, allowing you to remove the li element with the corresponding data-id value.

    var delete_btns = document.getElementsByClassName('delete-btn');
    
    var delete_task = function() {
        var li_id = this.getAttribute('data-id');
        document.getElementById(li_id).remove();
    }
    
    for (var i = 0; i < delete_btns.length; i++) {
        delete_btns[i].addEventListener('click', delete_task);
    }
    

Answer №2

Avoid assigning IDs to buttons to prevent duplicate IDs. Instead, attach the event listener when creating the button to instantly access the corresponding list item.

... 
var newButton = document.createElement("button");
newButton.addEventListener("click", function() {
    listItem.parentNode.removeChild(listItem);
});
... 

Answer №3

If you're looking to learn how to delete the element that was clicked, this code snippet might be helpful:

var listItem = document.querySelectorAll('li');

console.log(listItem)

listItem.forEach(function($li){
$li.addEventListener('click', function() {
  if($li.classList.contains('completed')) {
      $li.remove()
      }
  })
})
ul{
  list-style: none;
}
ul>li{
  background: #d2d2d2;
  margin: 10px;
  padding: 10px;
  cursor: pointer;
}
ul>li.completed{
  background: red;
}
<ul>
  <li>Task 1</li>
  <li>Task 2</li>
  <li class="completed">Task 3</li>
  <li>Task 4</li>
  <li class="completed">Task 5</li>
</ul>

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

Issue with Moment.js incorrectly formatting date fields to a day prior to the expected date

Currently, I am attempting to resolve a small issue in my code related to a tiny bug. In my React component, I have set an initial state as follows: const initialFormData = Object.freeze({ date: Moment(new Date()).format('YYYY-MM-DD'), pr ...

What is the method for applying background color to text within a textbox?

I am struggling to phrase this question properly and unable to find the solutions I need on Google. When searching, it only provides information on how to add an entire background color to a textbox, which is not what I am looking for. What I aim to achiev ...

Creating a BPMN web-based designer using JavaScript

In search of a web-based UI tool to design and save bpmn workflows as XML for integration with an Angular front end. As a starting point, I need to draw bpmn shapes. Does anyone have suggestions on the best method to accomplish this using JavaScript? I&apo ...

To enable communication between methods, you can easily add a property to a JavaScript class component

Is there a better way to communicate between methods in a class? class T extends React.Component { constructor(props) { super(props) this.a = false; } methodA { //will set 'a' in this method, maybe async. } ...

Angular 6 and Typescript: How to Map Objects in Arrays within Arrays

We currently have two arrays named speisekarte (consisting of 10 objects) and essensplan (containing 8 objects). const speisekarte = [ { id: 11, name: 'Kabeljaufilet', price: 3.55, type: 'with fish' }, { id: 12, name: 'Spaghet ...

What is the best approach for managing multiple HTTP requests in my specific situation?

I have a query about handling multiple HTTP requests in my code to ultimately get the desired result. Here is an outline of my approach: var customer[]; var url = '/api/project/getCustomer'; getProject(url) .then(function(data){ ...

Make sure to query MySQL database to see if the data already exists, and if not, go ahead and insert it using PHP

I am encountering difficulties in writing PHP code to insert values into a MySQL database only if they do not already exist. I am transmitting an array from JavaScript to a PHP file using $.ajax with the POST method. Do I need to include an additional &a ...

The malfunctioning of my Jquery datepicker

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <script src="jquery-1.11.1.min.js"></script> <script type="text/javascript"> $(document).r ...

How can one HTML form be used to request a unique identifier from the user, retrieve a record from the database, parse it into JSON format, and then populate an HTML page form using the

As someone who isn't an expert in any specific coding language, I have a knack for piecing things together to make them work. However, my current challenge is stretching my technical abilities a bit too far. Here's what I'm trying to achieve ...

Utilize ngModel within the <p> element in Angular 8

Here is some HTML code for displaying card information: <div class="col-md-4" *ngFor="let card of allCards"> <p class="card-text">Card Color: {{card.color}}</p> <button type="button" class=" ...

Transitioning to Firebase Authentication

I made the decision to transition away from firebase authentication. To accomplish this, I exported all firebase users along with their email addresses, hashed passwords, salt keys, and other necessary information. Next, I transferred them to a database a ...

Transmitting C# data to a JavaScript script through JSON serialization. Issue encountered: Character invalid

I'm facing an issue with sending data from my Entity Framework database to a JavaScript script on my webpage. Below is the snippet of code from my MVC Controller: public ActionResult Index() { var wordsToShow = db.Words.Where(w => w.O ...

Sharing a state object with another React file can be accomplished by using props or context to

My first React file makes an API call to retrieve data and save it in the state as Data. import React, { Component } from "react"; import axios from "axios"; import Layout from "./Layout"; class Db extends Component { constructor() { super(); th ...

The JSONP request connected to the user input field and button will only trigger a single time

Hello all, I'm new to this and have been searching the internet high and low to see if anyone has encountered a similar issue before, but haven't had any luck. I've been attempting to set up a JSONP request to Wikipedia that is connected to ...

The body content of the webpage needs to be updated without altering the header and footer, all while avoiding a page

On my website, I have a header menu that includes buttons for "home" and "about us." The default page is set to the home page. Within the home page, there is a specific link. When this link on the home page or the "about us" button is clicked, I want the ...

Pass the JavaScript variable and redirect swiftly

One of the functionalities I am working on for my website involves allowing users to submit a single piece of information, such as their name. Once they input their name, it is sent to the server via a post request, and in return, a unique URL is generated ...

Is there a risk of encountering issues when preloading (or caching) an entire website using Ajax?

I am in the process of developing a portfolio website for an architect that includes numerous images on various pages. The navigation is implemented using history.js (AJAX). To improve loading times and enhance user experience, I have devised a script that ...

Allow the NodeJS application to conduct self-updates using the NPM package manager

Hello, I'm currently exploring ways to add unique functionality to my NodeJS application, but I'm encountering some challenges. What I aim to achieve is as follows: I am interested in implementing a server code update feature from the client si ...

The footer on my page seems to be having trouble connecting with the div section above it, causing it to abruptly halt in the middle

After spending a considerable amount of time, I managed to make my footer responsive by sticking it to the bottom of the page regardless of which page you are on. The code that achieved this is as follows: position: absolute; bottom: 0; However, the issu ...

Preventing Body Overflow Without Affecting Iframe Overflow in Meteor.js

Currently, I am working on a project using Meteor for a Point of Sale (POS) system. For those unfamiliar with it, Meteor is a framework that allows for the use of JavaScript, jQuery, and various other web app scripting languages. The goal of this applicati ...