Adding li elements dynamically, how can we now dynamically remove them using hyperlinks?

Please refrain from using jQuery code, as my main focus is on learning javascript.

I am currently experimenting with adding li items dynamically to a ul when a button on the HTML page is clicked. Here's a sample implementation:

HTML:

<ul id="myList">
</ul>
<input id="myButton" value="Click Me" type="submit" onclick="addItem();"/>

Here's the JavaScript function addItem():

function addItem()
 {
  var l = document.getElementById("myList");  
  var today = new Date();
  var day2 = new Date();
  day2.setDate(today.getDate() + 30);
  var count = 1;

    while(today.valueOf() < day2.valueOf())
           {
            if(today.getDay() == 0)
                {
            var li = document.createElement('li');
            li.setAttribute('id', ['liID' + count]);
                    var month = today.getMonth();
                    var day = today.getDate();
                    var year = today.getFullYear();
                    var theDay = month + '/' + day + '/' + year + ' (Sunday)';
            li.innerHTML = theDay;
            l.appendChild(li);
            }
            today.setDate(today.getDate() + 1)
        count++;
           }
 }

Now, I would like to add a hyperlink next to each line item labeled 'Remove' so that users can click on it and delete the respective li. To achieve this, I attempted to create an anchor element using document.createElement('a'), but encountered issues triggering the deletion of the specific li. Here's my attempt:

Edit

 function addItem()
 {
  var l = document.getElementById("myList");  
  var today = new Date();
  var day2 = new Date();
  day2.setDate(today.getDate() + 30);
  var count = 1;

    while(today.valueOf() < day2.valueOf())
           {
            if(today.getDay() == 0)
                {
            var li = document.createElement('li');
            li.setAttribute('id', ['liID' + count]);
                    var month = today.getMonth();
                    var day = today.getDate();
                    var year = today.getFullYear();
                    var theDay = month + '/' + day + '/' + year + ' (Sunday)';
            li.innerHTML = theDay;
            l.appendChild(li);

            var a = document.createElement('a');
            a.setAttribute('href', '#');
            a.innerHTML = "Remove";
            a.onclick = function(e) {  
                        var liNode = e.target.parentNode;
                        l.removeChild(liNode); 
                                            };

                    li.appendChild(a);
                }
            today.setDate(today.getDate() + 1)
        count++;
           }
 }

Unfortunately, clicking the href link does not remove anything as expected...

Answer №1

A simple way to insert a new a element is by using the code snippet

var anchor = document.createElement('a');
. Additionally, you can set attributes either through setAttribute or directly like
anchor.href = 'http://yourpath.com';
. To add an event listener, you can utilize this snippet:

anchor.onclick = function(e) {
  // Cross-browser event handling
  e = e || window.event;
  var target = e.target || e.srcElement;
  // Assuming the anchor has been appended to a list item (li)
  var li = target.parentNode;
  var ul = li.parentNode;
  ul.removeChild(li);
}

Answer №2

Consider using the following code snippet:

let link = document.createElement('a');
link.onclick = function(event) { 
   // Code for obtaining the liNode in a cross-browser compatible manner
   let liNode;

   if (!event) var event = window.event;
   if (event.target) liNode = event.target.parentNode;
   else if (event.srcElement) liNode = event.srcElement.parentNode;
   if (liNode.nodeType == 3) { // Fix for Safari issue
        liNode = liNode.parentNode.parentNode;
       }
   // 'l' refers to the ul element which should have been defined earlier
   l.removeChild(liNode);
}
listItem.appendChild(link);

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

Refresh the PartialView only after clicking submit

I am struggling with updating only the contents of my partial view after clicking an input type="submit button. My goal is to refresh just the partial view and update it with the updated model from the controller code, without refreshing the entire page. S ...

Discovering methods to store browser credentials securely in jQuery

I need to prevent the login button from being enabled when either the username or password fields are empty. Check out the code snippet below: $(document).ready(function(){ $('input').on('keyup blur mouseenter', function(e) { ...

The incremental BR tag counter seems to be malfunctioning, there appears to be a missing element

Can anyone help me with the following code? I'm trying to add an incremental counter next to each BR tag in a lyric song, but it doesn't seem to be working as expected. <?php $lyrics = "<p>Every time when I look in the ...

The One-Click File Upload Dilemma

I have replaced the regular upload input + submit button with an icon. My goal is to automatically start the upload process when a file is chosen by the user. However, currently nothing happens after the file selection. <form action="upload.php" method ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

Dealing with numerous Ajax calls within a single Ajax request

I am utilizing the $http method in angularjs to retrieve multiple "parent" elements. Within the success method of these Ajax calls, I need to loop through the parent elements and make another Ajax call for each parent element to fetch its corresponding chi ...

Differences between $.ajaxPrefilter() and $.ajaxSetup() in jQuery Ajax

During my exploration of ajax in jQuery, I encountered two terms: $.ajaxPrefilter() and $.ajaxSetup(). It seems that both of these terms are related to making modifications to AJAX operations before they are executed or called by $.ajax(). Could someone p ...

Are JQuery functions affected when navigating between pages in smart-tables?

Apologies if this question has been answered before or seems obvious. I couldn't find a solution after searching, and as someone new to web development, I might be going in circles here. Issue: I've integrated the smart-table extension () into ...

Add more JSON entries to the data submission in Express

Purpose: My goal is to ensure that the JSON data I submit is formatted correctly when it arrives in the JSON file, regardless of the number of entries I submit. Challenge: Currently, the data I submit does not append properly in the JSON file. It appear ...

"Sending a POST request from the smartphone application client developed using the Meteor

I'm currently working on a simple mobile app with Meteor that aims to send user location data to a geospatial database or server. However, I'm facing some challenges and uncertainties about the feasibility of this task using Meteor. The issue ari ...

Having Trouble with Your Instafeed Script

I've been working on a project that involves integrating an Instagram feed into a website. However, I'm facing difficulties getting it to function properly. Here's the code that I have implemented. <script type="text/javascript"> ...

Using regular expressions to replace strings in JavaScript

I have a URL that resembles the following http://localhost:12472/auctions/auction-12/lots/sort/something/12 I am looking to switch it out with this new URL http://localhost:12472/auctions/auction-12/lots/sort/somethingelse/12 Here, somethingelse can be ...

Passing the value of each table row using Ajax

On my webpage, I have a list of orders displayed. I'm facing an issue where the value of each row in the table is not being passed correctly to my controller and database when a user clicks on a button - it always shows null. Can someone please assist ...

Transmitting an Array Using an Ajax Call

Is there anyone knowledgeable in Ajax here? I'm struggling with sending a javascript array in an ajax request. Can someone provide me with an example of how the ajax request should be formatted? My goal is to gather all the javascript data, package it ...

Could a javascript loop be created to continuously activate a button with each iteration?

I have just started learning javascript and I am in the process of creating a website where users can change the background by simply clicking on a button. It's working perfectly fine so far, but I want to add another feature where the background imag ...

Using Angular with a hapi.js server that supports JSONP data requests

In my project, there is an endpoint specifically set at /api/profile that accepts post parameters. var http = require('http'); var serverConfig = require('../server.config.js'); var request = require('request'); module.expo ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

Using jQuery, check if the input contains any phrases from the array that are suitable for children

I stumbled upon some code designed for a chat system. My plan is to implement it as a child-friendly global chat, so that I can avoid any blame associated with inappropriate content. The basic premise of the code involves checking user input against an arr ...

Does the process of reading a `stream` consume resources in Node.js?

Node.js utilizes a stream as an abstract interface for handling streaming data. The node:stream module offers an API to implement this stream interface. During my exploration of NodeJs streams, I encountered confusion over whether a stream was involved in ...

I am having trouble with searching for places using the Google API in my Node

Recently, I've been working on integrating the Google Maps API places feature into my project. Thankfully, I came across an npm module that simplifies the process of connecting it to node. Check out the npm module here! After downloading the module ...