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

Loop through a non-array or non-object / handling both arrays and non-arrays equally

Sometimes, I find myself needing to handle arrays and single objects in a similar manner. For instance, I may have an object property that can be either an array or just a string (like the scale property): [ { "name": "Experiment type14", "id": ...

I need help with creating an AJAX JSON call using Angular. Let me share the JavaScript function that I currently have

When a button is clicked, the function below is called. It retrieves data from a JSON file and stores it if a success message is received. Here is a screenshot of the returned data. My JavaScript function is working correctly, but I am new to Angular and l ...

How do I determine the appropriate image type to use?

I'm a beginner in the world of Node.js and I'm currently working on an application that stores image files. However, I am unsure about what type of data the images should be. const userSchema = new mongoose.Schema({ userImage: { type ...

What is the best way to include message body in CDATA using strophe?

I have a task to create messages in a specific format by using the following code: $msg({to: 'user', from: 'me', type: 'chat'}).c("body").t('some data'); This code generates the message structure as follows: <m ...

Creating a responsive and expandable table using HTML and JavaScript

I need help with making my html table resizable in a vertical direction. The cells can overflow if there isn't enough space, so I want to allow users to stretch the table by dragging and extending the bottom edge. Can anyone provide guidance on how to ...

Increasing a variable in MongoDB using Meteor.js based on the value of a variable in a separate document

I am facing an issue similar to this: I am struggling to modify multiple documents simultaneously. click: function() { var power = Meteor.user().power; var mult = Meteor.user().mult; Meteor.users.update({ _id: this.use ...

The value of Yargs.argv is consistently displayed as [object Object]

In my Ubuntu 16.04 environment, I enrolled in a node.js course on Udemy. Following the instructor's guidance, I initially used the exact version mentioned and later updated to the latest version (11.0.0). Surprisingly, both versions yielded the same o ...

A step-by-step guide on generating a dynamic JSON file with JavaScript

I am in need of generating a JSON structure that follows this specific format: {"content": { "properties": { "area_id": "20", "origin": "3", "axis": "1", "x_start": "00", "x_end": "99", "y_start": "00", ...

Filter JSON data deeply for specific values

I am attempting to filter JSON data based on user checkbox selections in JavaScript. The challenge I'm facing is implementing multi-level filtering. The data has two dimensions that need to be filtered: first by OS selection and then by a selected que ...

Angular 4 encounters a hiccup when a mistake in the XHR request brings a halt to a

In my Angular 4 application, I have implemented an observable that monitors an input field. When it detects a URL being entered, it triggers a service to make an XHR request. Observable.fromEvent(this._elementRef.nativeElement, 'input') .debou ...

When the CSS animation has finished in JavaScript

I am currently developing a game using HTML/JavaScript, and I have implemented a "special ability" that can only be activated once every x seconds. To indicate when this ability is available for use, I have created a graphical user interface element. Since ...

Node.js - Error: JSON.Parse and JSON.Stringify are not recognized as functions

Is it possible to convert a string to JSON and vice versa without any additional npm packages? I am currently using JSON.Stringfy in my router.js file. Are there any specific npm modules that need to be added to the project in order to use the JSON.Stringf ...

Guide on exporting values from a Promise within an imported module

Recently, I encountered a challenge where I needed to integrate a pure ESM package into a non-module. Unfortunately, modifying the script to accommodate this requirement was not an option. To tackle this issue, I turned to using the import() function (als ...

What is the best way to use res.sendFile() to serve a file from a separate directory in an Express.js web application?

I have a situation within the controllers folder: //controler.js exports.serve_sitemap = (req, res) => { res.sendFile("../../sitemap.xml"); // or // res.send(__dirname + "./sitemap.xml") // But both options are not working }; ...

Node.js API requests often result in undefined responses

As a newcomer to Node.JS, I am currently experimenting with calling a REST API using the GET method. I have utilized the 'request' package available at this link. While the call functions correctly, I encounter an issue when attempting to return ...

Creating a personalized progress bar that reflects real-time data from an external API

I have developed an API that sends scores if someone solves math, chemistry, or physics problems correctly. The API responds with a JSON object like this: { "scores": { "maths": 28, "chemistry": 9, "physics": 26, } } When a person complet ...

What are the solutions for resolving the error "npm run build failed to compile React JS?"

Having trouble creating an optimized production build... Compilation failed. Module not found: Error: Unable to locate './App' in '/Users/qadeer/Desktop/Khazan/guardman/src' Did you mean 'App.js'? BREAKING CHANGE: The request ...

Implementing child components rendering in a React application using TypeScript

Just a little background information: I am attempting to build a carousel with pagination using ReactJS. Here is the code snippet I currently have: interface HTMLCarouselT { children: Array<JSX.Element> size: number; } const HTMLCarousel = ({ch ...

Adapting the column width to display or hide content with CSS styling

I have a row with 2 columns. The left column contains my main content and the right column is a chatroom. I would like users to be able to minimize and open the chatroom, which I already know how to do. However, when the chatroom is open, I want the left ...

JavaScript Paint Brush Tool Powered by HTML5

I am looking to create a smooth and clean opacity brush. Here is an example of the drawing line I want: This is the second picture I managed to achieve: When I move the cursor quickly, there are fewer circles in the drawing line. ...