Here's a way to programmatically append the same icon to multiple li elements generated using document.createElement:

I am new to creating a to-do app and need some guidance. When a user enters a task, I successfully create a list item for that task. However, I am unsure how to add a delete icon next to the newly created li element. Can someone please help me out? Below is my current code:

const inputArea = document.querySelector('#input');
const allTasks = document.querySelector('#list');
const deleteTask = document.querySelector('#close');

function collectInfo() {
  if (inputArea.value === '') {
    alert('Please enter a task to add!');
  } else if (inputArea.value != '') {
    const node = document.createElement('li');
    const newTask = allTasks.appendChild(node);
    newTask.textContent = inputArea.value;
  }
}

const clicked = document.querySelector('#add');
clicked.addEventListener('click', collectInfo);

Answer №1

If you're looking to spice up your function, here's another way to add tasks. Instead of simply appending them, consider using the += operator for each task. This will provide a different approach and make adding the delete button a breeze.

function collectInfo() {
  if (inputArea.value === '') {
    alert('please type a task to add');
  } else if (inputArea.value != '') {
    allTasks += `<tr><td>${inputArea.value}</td><td><button 
    id="delete">Delete</button></td></tr>`
  }
}

In this scenario, I used a table structure which you can also implement. Simply change your #list to <table id="list>

Once that's done, don't forget to connect the delete button to your new task.

To achieve this, assign a unique id to each task so it can be linked with the corresponding button by that same id.

Alternatively, you could take a completely different route by storing each new task in an Array, then utilizing a foreach loop to display the tasks and link the delete button to the array index instead.

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

When the onLeave event of fullPage.js is activated

I am struggling to implement two CSS events when transitioning between sections on a fullPage.js application. To see my current progress, you can view the following fiddle: http://jsfiddle.net/pingo_/67oe1jvn/2/ My objectives are as follows: To modify t ...

What is the best way to compare dates in JavaScript using this particular format?

Is there a way to compare the current date and time in JavaScript with the specific format of '2016-06-01T00:00:00Z'? I am receiving the date format '2016-06-01T00:00:00Z' from the backend, and I need to verify it against today's ...

Stop the annoying page flicker in Next.js 12 by implementing a custom dark mode using Tailwind CSS classes

Is there a way to prevent the page flash when implementing dark mode in Tailwind CSS using classes in Next.js v12 without relying on third-party packages like next-themes? I have explored different solutions: This StackOverflow Q&A How to fix dark mo ...

Tips for creating the X Mark using SVG and CSS

I'm struggling to create an animation of an "X" checkmark sign (for failure). Although I found a great example of an animated checkmark sign for success, the code uses a curve-bezier design that I can't replicate for the "X" sign. If anyone cou ...

Accordion elements that are active will move all other content on the page

I am currently working on creating an accordion using the following code: https://codepen.io/rafaelmollad/pen/JjRZbeW. However, I have encountered a problem where when clicking on one of the accordion items, the content expands and pushes the title upward. ...

Creating PNG and JPEG image exports in Fabric.js with the help of Node.js

Exploring the wonders of Fabric.JS specifically designed for Node.JS, not intended for web applications, I've successfully created a Static Canvas and added a rectangle to it. Now, it's time to export the image. Take a look at my code snippet bel ...

Issue with horizontal navigation in CSS

I'm struggling with styling my CSS navigation bar. The last list item is moving to a second line, which really messes up the look of my website. Can someone take a look at my code and point out what I'm doing wrong? Thank you in advance. HTML: ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

Updating Arrays in Node.js isn't happening as expected

Hello, I have a function that I am calling from my controller like this: var getLastPoll = await socketModel. getPollOptionsByPollId(data.poll_id); but the controller is returning an empty array as a result. However, when I log the result in my model, ...

implementing a JavaScript function and declaring a variable from an HTML source

On my webpage, I have a feature that gathers a large amount of data using jQuery. My goal is to limit the number of results displayed by changing the shown results dynamically to create a false-page effect. This functionality is all handled through a singl ...

Global asynchronous functionality can be enabled in JavaScript

Wouldn't it be convenient to have the option to enable async functionality in the global scope? This way, there would be no need to wrap all asynchronous operations within a function. I'm curious if this is achievable in browser JavaScript or per ...

Blurring images with a combination of jQuery Backstretch and Blurjs

I have a background image displayed using Backstretch and want to apply Blur.js to blur elements on top of it. However, when I try to use Blur.js on the backstretched image, it doesn't work. I believe this is happening because Blur.js uses the CSS pro ...

Attempting to display numerous react components on various divs instead of just one ID

Currently, I am facing a challenge in creating multiple react comment boxes. The package I am using is based on #id instead of class, which resulted in only rendering one box instead of all. To resolve this issue, I attempted to switch from GetelemntbyID t ...

What is the best way to retrieve environment variables from an NPM package in an Angular 5 application

Is there a method for my node module, created from an Angular 5 application, to access the environment variable from the Angular 5 application (environments/environment.ts)? Perhaps Angular 5 exports its environment variables to JavaScript global variables ...

grab the destination URL from the embedded frame

Thank you for your attention. I am working with three iframes spread across different HTML documents. Here is how they are organized: In the file iframemain.html, there is: <iframe src="iframeparent.html" width="100%" height="600"> </iframe> ...

Modifying the color of a specific div using jQuery

I am attempting to develop a function that changes the background color of a div when a user clicks on it and then clicks on a button. The value needs to be saved as a variable, but I'm having trouble getting it to work because it keeps saying that th ...

Encasing newly inserted child components within my designated slot

If I have a component with a single slot and instead of simply rendering all its children, I want to wrap each element individually, the following approach can be taken: Vue.component('MyElement', { render: function(createElement){ for (l ...

I encountered an issue when sending a PATCH request via Hoppscotch where the request body content was returned as 'undefined', although the username and ID were successfully

const express = require("express"); const app = express(); const path = require("path"); let port = 8080; const { v4: uuidv4 } = require('uuid'); app.use(express.urlencoded({extended: true})); app.set("views engine", ...

Using JavaScript with namespaces in C#

I am currently trying to explore AJAX and web services through self-teaching using C# and JavaScript. After doing some research on Google, it seems like I might be facing a namespace problem. Here is the snippet of my code: using System; using System.Col ...

The output generated by grunt-contrib-handlebars differs from that of the handlebars npm task

Looking for some help with a problem similar to the one mentioned in this Stack Overflow question. Since that question hasn't been answered yet, I decided to create my own post. I'm currently attempting to precompile my handlebars template files ...