adding items from a menu dynamically with a delete button with option of removing them with javascript

StackOverflow https://stackoverflow.com/questions/22229815

  •  06-06-2023
  •  | 
  •  

سؤال

//This is a beginning AJAX lab. Not sure how to attach my code, so I gave min. code

//create element and text node with a button to delete each burrito if they change mind

function addingToCart(){
  h3 = document.createElement("h3");  
  document.getElementById("cart").appendChild(h3);//a div in my html shown above//
  message = document.createTextNode(itemMessage); 
  h3.appendChild(message);  
  deleteBtn = document.createElement("BUTTON");
  h3.appendChild(deleteBtn);
  var textBtn = document.createTextNode("Delete"); 
  deleteBtn.appendChild(textBtn);
  h3.id = "deleted"; //this will not be unique this way.  :(
}

    deleteBtn.onclick = function(){
        removeBurrito();
    } 

    function removeBurrito(){h3.parentNode.removeChild(h3); }

This works great if I only add one item then delete it. But If I add 2 items to my cart, the 2nd item will throw a null error:TypeError: h3.parentNode is null

I think I have to create individual id's dynamically with a loop or array, but do not know how.

هل كانت مفيدة؟

المحلول

I'd suggest you to use jQuery.

A solution to your problem could be this:

Add

deleteBtn.onclick = function(){
    removeBurrito(this);
}

into the addingToCart function.

Update removeBurrito function into the following one:

function removeBurrito(element) {
    element.parentElement.remove();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top