What is the best way to delete elements from both the DOM and an array simultaneously

I am currently working on a task management application where users can input items into a list. The entered item is displayed on the page and also added to an array named "items".

While adding and removing items from the page works smoothly, I'm facing challenges with removing items from the array itself. It seems that synchronizing the removal of items from both the page and the array is not as straightforward as I expected.

The array will be utilized for another purpose, so it's crucial to keep it updated. I have experimented with using the splice method to remove items from the array but encountered some issues in implementation.

I even tried revising my approach by first adding items to the array and then dynamically displaying them on the page using a for loop. However, this didn't resolve the problem either.

If anyone can offer guidance or assistance, I would greatly appreciate it! You can access the live version of the app through the following link hosted on my Neocities account:

Below is a snippet of the code I am currently working on:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #myList {
            list-style: none;
        }
        li {
            padding: 10px;
            max-width: 300px;
            background-color: rgb(186, 255, 129);
            font-size: larger;
            font-weight: bold;
            border-style: double;
            border-radius: 10px;
            text-align: center;
            margin: 5px;
        }
        .remove-btn {
            float: right;
            background-color: red;
            color:black;
            
        }
        #itemAdd {
            padding: 10px;
            font-size: larger;
            text-align: center;
        }
        #itemName {
            padding: 10px;
            max-width: 300px;
            font-size: larger;
            font-weight: bold;
            border-style: double;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container main">
        <form action="" method="post">
        <input type="text" id="itemName">
        <button onclick="addItem()" id="itemAdd">ADD</button>
        </form>
        <div>
            <ul id="myList">
                
            </ul>
        </div>
    </div>
    <script>

        let items = [];

        const addItem = () => {
            event.preventDefault();
            let myList = document.getElementById('myList');
            let listItem = document.createElement('li');
            listItem.innerText = itemName.value + "  ";
            myList.append(listItem);
            let removeButton = document.createElement('button');
            removeButton.innerText = "-";
            removeButton.className = "remove-btn"
            removeButton.addEventListener('click', removeItem);
            listItem.append(removeButton);
            items.push(itemName.value);
            document.forms[0].reset();
        }

        const removeItem = () => {
            let item = event.currentTarget.parentNode;
            item.remove();
            let itemIndex = items.indexOf(item);
            items.splice(itemIndex, 1);
        }
    </script>
</body>
</html>

Answer №1

I'm diving into code blindly here, so please be patient if there are imperfections.

The issue lies in the line

let itemIndex = items.indexOf(item);
where you are searching an array of strings with a node (a sort of DOM object).

Instead, consider adding a data-* attribute to your <li> element, where you store what the user types, and then extract that using the dataset property. Subsequently, utilize that string to search through your list array.

I've taken the liberty of restructuring some of your code for improved readability.


    let items = [];
   
    var createListItem = (text) => {
        let listItem = document.createElement('li');
        listItem.innerText = text;
        listItem.setAttribute('data-value', text); // adding a data attribute
        
        return listItem;
    }
    
    var createRemoveButton() {
        let removeButton = document.createElement('button');
        removeButton.innerText = "-";
        removeButton.className = "remove-btn"
        removeButton.addEventListener('click', removeItem);
        
        return removeButton;
    }

    const addItem = () => {
        event.preventDefault();
        let userInput = itemName.value.trim();
        let myList = document.getElementById('myList');
        let listItem = createListItem(userInput);

        listItem.append(createRemoveButton());
        myList.append(listItem);
        
        items.push(userInput);
        document.forms[0].reset();
    }

    const removeItem = (event) => {
        let item = event.currentTarget.parentNode;
        let userInput = item.dataset.value; // extracting the data attribute
        item.remove();
        let itemIndex = items.indexOf(userInput);
        items.splice(itemIndex, 1);
    }

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

Tips for displaying a table with a button click

I am struggling to figure out how to embed a table inside a button in order to display the table when the button is clicked and hide it when clicked again. Below is the code I have been working with: function toggleTable(){ document.getElementById ...

How can I determine if a collision has occurred with any rectangle in a given array using Pygame?

I am currently dealing with an array of Box objects, each containing a rect attribute. My goal is to determine if my player collides with any of the rects in this array. However, I have encountered an issue where the collision detection logic only seems to ...

Using AJAX to implement CSS class effects

Currently, I am facing an issue with applying a highlighting effect to list items in a menu using a snippet of code. The menu items are just POST and I have created a second step to the menu where I want to apply the same effect to any element with a class ...

The navbar's background sections have various colors

Struggling to grasp React? Want to create a partially transparent Bootstrap navbar and customize the color, but encountering inconsistency due to the main background color setting. How can this be resolved? My App: function App() { return ( < ...

Merge two arrays into a single array and assign keys to the elements

I've been grappling with this problem for quite some time. The challenge I'm facing involves merging two arrays. Here is the initial input: { "array_one": { "mrnreference": [ { "key_0": "18DK00310020B11A84" ...

Tips on finding the mean of an array using PHP

Within this array code, I have: $numers = array ( array(198,208,109,11,636), array(198,188,84,55,756), array(194,206,113,13,531), array(184,213,127,18,101), array(194,213,127,23,110), array(984,213,127,44,125), array(184,213,127,88,980), ar ...

Guide on how to send a variable to the footer section in Jade using Node.js

In my footer with Jade, I want to show a variable named total. .container .footer hr(style='margin: 30px 0 10px 0;') p #{total} entries in this database. link(rel='stylesheet', href='/css/style.css') scri ...

Retrieving the result of a callback function within a nested function

I'm struggling with a function that needs to return a value. The value is located inside a callback function within the downloadOrders function. The problem I'm encountering is that "go" (logged in the post request) appears before "close" (logged ...

Sending data from a child component to its parent counterpart

A component called cartComponent has a data property named cartCount which increases every time a new item is added to the cart. I want to utilize this value to update another value in the template that is not part of the component. Is it achievable? Bel ...

Learn how to toggle a specific div by clicking on an image generated from an ngFor loop in Angular version 11

One issue I am facing is that I have multiple sections containing image info and details. When I click on a specific image, the corresponding details should toggle. Everything works fine, however, if I click on another image without closing the previous ...

Mongoose Express: Limiting increments to a maximum of 5

Currently, the essential functionality implemented is 1 click = 1 vote. The system successfully updates a vote parameter in MongoDB and increments it as expected. However, after approximately 5 votes, the incrementing process halts. Upon refreshing the bro ...

How can I implement an AJAX request with MongoDB in Node/Express?

Let's begin with a simple webpage: an HTML Form, a button, and a div-box. When the button is clicked, the Form data will be sent via AJAX. The data will then be stored in MongoDB and retrieved into the div-box seamlessly without any page refresh. A ...

Refresh Rails 4 instance variables seamlessly without reloading the page

Is there a method to update an instance variable in the view without refreshing the page? I'm using AJAX to post and create a new record. After creating the record, I want it to be added to the current instance variable. Let's say I have an act ...

How to automatically close a Bootstrap modal after submitting a form

I am facing an issue with a Bootstrap modal dialog that contains a form. The problem is that when I click the submit button, the form is successfully submitted but the modal dialog does not close. Here is the HTML code: <div class="modal fade" ...

transferring information from Node.js/MongoDB to the front-end (invisible in the browser)

I am trying to retrieve data from a mongodb database and pass it to the front-end. The function I have written works in the console, where I can see an array containing elements. However, when I try to view it in the browser, it shows undefined. I am worki ...

Retrieve the total count of shops from the previous 12 months within a MongoDB database

I am looking to track the cumulative number of shops over the past 12 months. Sample Collection { _id: '5f3d4e5e01e06f0007335233', name: 'Walmart', createdAt: '2020-08-22T17:42:09.908+00:00' } Currently, I am able to re ...

What are some ways I can safeguard my CSS from injected elements?

I have created an HTML widget that is inserted into various websites without the use of iframes. However, I am encountering issues where the CSS of some sites is affecting the appearance of my elements, such as text alignment, underlining, and spacing. Is ...

What is the best method for storing both strings and floating point numbers in one np.savetxt file?

Python newbie seeking help! inputs = ["eos", 5, 60, 2000, 3] String 'eos' and integers make up the list. Need to store it like this: np.savetxt(path + '/inputs.txt', inputs, delimiter=" ", header = 'Eos Pressure Radius Nt Sigma& ...

Validate if the token has expired by utilizing this JWT library

My token configuration looks like this: jwt.sign( { user: pick(user, ['_id', 'username']) }, secret, { expiresIn: '2m' } ); However, when attempting to verify if the token has expired, the following code isn ...

What are the steps to set up rollup with Vue?

Working on a project utilizing Vue.js and bundling with Rollup. Shown below is the content of my rollup.config.js file import vue from 'rollup-plugin-vue2' import less from 'rollup-plugin-less2'; import buble from 'rollup-plugin- ...