Search code examples
javascriptlistdynamic-arrays

How to create a dynamic list, which removes deleted items from an array in JS?


I have created a list, which creates a new paragraph, with the value of the input field and adds the value of the input field into an array, if the add-Button is pressed. Each paragraph has a delete Button, which removes the paragraph visually, if pressed. Now I want that the Input of the paragraph also gets removed from the array.

For example lets say, that the array usernames includes usernames[1] = Lukas, usernames[2] = Martin, usernames[3] = Bob and I want to delete the paragraph, which includes Martin. How can I create a function, where the paragraphs content also automatically gets removed from the array usernames. I would be very thankful for some help. Here is my code:

let name = document.getElementById('name');
let addButton = document.getElementById('button');
let output = document.getElementById('output')

let usernames = [];

addButton.addEventListener('click', function() {
    usernames.push(document.getElementById('name').value)
    console.log(usernames)

let paragraph = document.createElement('ul')
    paragraph.innerText = document.getElementById('name').value
    output.appendChild(paragraph)

let deleteButton = document.createElement('button')
    deleteButton.innerHTML = "X"
    paragraph.appendChild(deleteButton)

    deleteButton.addEventListener('click', function() {
        output.removeChild(paragraph)
    })
})

Solution

  • Thank you for your answers, but unfortunately the inner Text of the delete Button gets added to the array content, if something gets deleted, because it is part of the 'li' component. I simply created a div which includes the name and the delete Button to solve the problem. But nevertheless thank you for your help. Thats the working code:

    const user = document.getElementById('user');
    const add = document.querySelector('.add');
    const list = document.querySelector('.list')
    
    let usernames = [];
    
    add.addEventListener('click', function() {
      let name = user.value;
      user.value = '';
      usernames.push(name);
      console.log(usernames);
    
      const paragraph = document.createElement('div')
      paragraph.style.display = 'flex'
    
      const item = document.createElement('li');
    
      item.textContent = name + '  ';
      list.append(paragraph);
      paragraph.append(item)
    
      const del = document.createElement('button');
    
      del.textContent = "X";
    
      paragraph.append(del);
    
      del.addEventListener('click', function() {
        this.closest('div').remove();
    
        usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
    
        console.log(usernames);
      });
    });