0

I have been wanting to modify this code to include a delete button , so when the button is clicked the list item deletes but its not been working.

//ORIGINAL CODE//

let elList, addLink, newEl, newText, counter, listItems, oldEl, removeLink; 

elList  = document.getElementById('list');             
addLink = document.querySelector('a');               
counter = document.getElementById('counter'); 

oldEl = document.getElementsByTagName('li');

removeLink = document.getElementById('delete');      


function addItem(e) {                                   
    e.preventDefault();   
    newEl = document.createElement('li');

newText = document.createTextNode('New list item');

newEl.appendChild(newText);                         

    elList.appendChild(newEl);                             
  }

function updateCount() {                                 
  listItems = elList.getElementsByTagName('li').length;  
  counter.innerHTML = listItems;                        
}

addLink.addEventListener('click', addItem, false);      
elList.addEventListener('DOMNodeInserted', updateCount, false); 

//WHAT I TRIED//
function removeItem(){

e.preventDefault();

oldEl.parentNode.removeChild(oldEl);
} 

removeLink.addEventListener('click', removeItem, false);

I expect when i Click on the delete button, one of the list items dissapears but its just no working. Please i Need some help as i hav been stuck here for a very long time

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • 1
    Please always include ALL the relevant code (HTML, CSS, JavaScript) so that we can replicate your issue and provide a working solution. As it is now, for all we know, your HTML could be the problem. – Scott Marcus Aug 30 '19 at 13:39
  • From what I can see, you have `oldEl = document.getElementsByTagName('li');`, which returns a node list and `oldEl` is what you are trying to remove with `oldEl.parentNode.removeChild(oldEl);`, but a node list doesn't have a `.parentNode`, nor does it have a `.removeChild()`. If you open your developer tools and look at the console, you will most likely see these errors there. – Scott Marcus Aug 30 '19 at 13:42

1 Answers1

0
oldEl = document.getElementsByTagName('li');

getElementsByTagName returns an NodeList, you cannot delete it by doing this:

oldEl.parentNode.removeChild(oldEl);

If you want to delete all items in the oldEl do this:

function removeItems(){
  oldEl.forEach((item) => {
    item.parentNode.removeChild(item);
  });
} 
volcanic
  • 312
  • 1
  • 6
  • *getElementsByTagName returns an array* <-- No, it doesn't. It returns a node list, which is an ["array-like" object](https://stackoverflow.com/questions/29707568/javascript-difference-between-array-and-array-like-object). – Scott Marcus Aug 30 '19 at 13:46