Get rid of just this one specific element using jQuery

I have implemented a feature where tasks are dynamically added to a list when the input is entered and its length is less than or equal to 30 characters, followed by clicking a button.

Each task comes with a trash icon for removal, sourced from an external library called ionicons.

The issue I am facing is that when the trash icon is clicked, it not only removes the targeted task but also all tasks created after it in the list.

To add tasks, I am using the prepend method for li elements.

Below is a snippet of the code:

$('#addNewTaskBtn').click(function () {
    var inputText = $('#dayTask').val();
    var trashIcon = '<i class="ion-trash-b"></i>';
    var newTask = $('<li />', { html: inputText + " " + trashIcon });

    // Clearing the input field after click
    $('#dayTask').val('');

    if (inputText.length && inputText.length <= 30)
        $(newTask).prependTo('ul.dayList');

    $('.ion-trash-b').click(function () {
        $(this).parent().remove(); // changed this line to target the parent li element
    });
});

Now, my question is: How can I modify the code so that only the specific Li element associated with the clicked trash icon is removed, without affecting other Li elements that were created later?

Thank you for your assistance.

Answer №1

$('.ion-trash-b').click(function(){
  $(this).parent().remove(); // or $(this).closest("li").remove();
});

Alternatively, you can set it to load and apply to all upcoming trash icons using event delegation

$(function() {
  $("#listContainer").on("click",".ion-trash-b",function(){
    $(this).parent().remove();// or $(this).closest("li").remove();
  });
});

Make sure to replace listContainer with the actual ID of the UL element.

Answer №2

One way to handle deleting tasks is by removing the nearest li element when the ion-trash-b icon is clicked. Since your elements are dynamically created, it's recommended to utilize event delegation for handling the click event on ion-trash-b, as shown below.

$('#addNewTaskBtn').click(function () {
    var inputText = $('#dayTask').val();
    var trashIcon = '<i class="ion-trash-b"></i>';
    var newTask = $('<li />', { html: inputText + " " + trashIcon });

    // Clearing the input field after clicking
    $('#dayTask').val('');

    if (inputText.length && inputText.length <= 30)
        $(newTask).prependTo('ul.dayList');        
});

$('body').on('click', '.ion-trash-b', function () {
    $(this).closest('li').remove();
});

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

Favicon in browser blinks when hash changes

Whenever I adjust the hash location using either document.location.hash or window.location.hash, there seems to be a slight 'blinking' effect in most browsers. It's quite unattractive and I need to find a way to prevent it, especially since ...

The animation is disrupted by multiple clicks in jQuery

Here is a basic form example: <form id="form" action="file.php" method="POST"> <input class="form-control" type="number" name="p" value="0"> <label for="p">Text</label> <input class="form-control" type="number" name=" ...

Exploring AngularJS: Effortlessly Retrieving Object Values

HTML: <div ng-app = "" ng-controller = "personController"> <p>Persoon: <select ng-model="persoon"> <option ng-repeat="person in persons">{{person.FirstName}} {{person.FamilyName}}</option> & ...

Utilizing React Selector: Propagating the onChange Event Up Two Components

Struggling to pass an onChange event from React selector through two components back up to the parent App. The issue is that e.target.value is coming back as undefined, indicating that the event might not be returning properly. Can someone pinpoint what&ap ...

Issue with binding the expanded property in Angular Expansion Panel

Including Angular code within my HTML, I have Admin and User Main menu items available. <a id="adminId" (click)="sideNavLink($event)">Admin</a> <mat-accordion class="mat-accordion-setting"> <mat-expansi ...

What is the best way to use HTML and CSS to center images and headings on a webpage?

This task is really testing my patience... I'm attempting to create a layout that resembles the following: Logo img|h1|img The horizontal lines flanking the subtitle serve as a visual guide, like this --- Subtitle --- Below is the snippet of H ...

What are your thoughts on the size of a React component being 500 lines long?

Currently, I am in the process of constructing a Table component that includes filters and requires an extensive amount of logic. Additionally, I have incorporated material UI which tends to add multiple lines of code. Despite these elements, I feel that ...

Currently in the process of executing 'yarn build' to complete the integration of the salesforce plugin, encountering a few error messages along the way

I've been referencing the Github repository at this link for my project. Following the instructions in the readme file, I proceeded with running a series of commands which resulted in some issues. The commands executed were: yarn install sfdx plugi ...

When attempting to install React Native on a Mac using the "npx react-native init MyTestApp" command, the

PROBLEM I am encountering difficulties while attempting to install and execute the react native todo command - npx react-native init MyTestApp on my MacBook Pro. The specific challenges I am facing are: The detailed github issue can be found here: here ...

Having an issue where my meshes disappear when using the Unreal Bloom render pass in ThreeJS. Any ideas on what might be causing

Just starting out with Three and I'm really enjoying it, but I seem to be stuck on a problem. The code in this gist might help: https://gist.github.com/TheeBryanWhite/a7a2041fc8848a0ba449897883c43bdc Initially, the first render functions correctly b ...

The request returned a 404 (Not Found) error message when trying to navigate using AngularJS

Currently, I am working on building a straightforward application using Ionic and Angular. To test my progress locally, I have set up a simple server by running Ionics ionic serve command. Below is the snippet of my playlist.html code, where I intend to s ...

Error: Axios header not refreshing automatically in React. User must manually refresh the page

After logging in, I want to update the JWT token in the header before redirecting to the home page. Login.tsx ... const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); const data = new FormData(event.curr ...

Reload a jquery pop up upon closing a pop up window

I have a modal pop up that appears after clicking an ASP button : <div class="form-group"> <asp:Button ID="btnBrand" runat="server" Text="Add brand" CssClass="btn btn-info" OnClick="btnAdd_Click" /> </div> Code Behind : protected ...

I am interested in creating a design where two DIVs are layered on top of each other with one having transparency, allowing visibility through to the background DIV. This can be achieved using a combination of

Looking to enhance the visual appeal of my website, I decided to incorporate a background image within a div. To add more depth and creativity, I am now striving to overlay a semi-transparent black box on top of the image. This overlay will not only allo ...

Can anyone explain why the background images aren't appearing correctly on iPhones and iPads?

I've been attempting to resolve the issues on this page for what seems like forever. The site in question is theafropick.co.uk. All devices seem to function properly except for iPads and iPhones, where the section with 6 tiles disappears entirely. ...

Passing the v-model property from a child component to a parent in VueJS

Consider a scenario where there is a Vue component structured like the following: Vue.component('child-comp',{ props:['name', 'val'], data: function(){ return { picked: '' } }, ...

Node 18 is having trouble locating NPM and is unable to locate the module './es6/validate-engines.js'

Previously, I attempted to install Node.js without any issues. However, this time around, I am encountering difficulties accessing the npm package. While I can successfully retrieve the version of Node.js after installation, attempting to check npm -v or w ...

Issue with jQuery tabs and removal request

Currently, I am working on a website and have implemented a jQuery tab. However, I would like it to remember the selected tab even after refreshing the page so that it doesn't revert back to the first tab every time. You can view my site at . The tab ...

AngularJS does not function upon reloading the browser

I am currently working on a new project that involves the following components: Node.js (v0.10.37) Express micro framework Jade templating engine Angular.js (latest) Material design library (material.angularjs.org) Jquery One issue that I am facing is r ...

An unusual problem stemming from jQuery/AJAX arises when variables within a function fail to update while a click

I've been struggling with a small issue for the past three days that I just can't seem to resolve. It doesn't seem to be a coding error, but rather a misunderstanding of variables and why the onClick event isn't functioning properly. H ...