Search code examples
javascriptbuttonremovechild

javascript dynamically remove text


I have successfully created a button which adds text to the webpage however I do not know a viable way to remove text once this has been created. The js code I have is:

    var addButtons = document.querySelectorAll('.add button');

function addText () {
  var self = this;
  var weekParent = self.parentNode.parentNode;
  var textarea = self.parentNode.querySelector('textarea');
  var value = textarea.value;
  var item = document.createElement("p");
  var text = document.createTextNode(value);

  item.appendChild(text)
  weekParent.appendChild(item);
}

function removeText() {
  //document.getElementbyId(-).removeChild(-);
}

for (i = 0; i < addButtons.length; i++) { 
    var self = addButtons[i];
    self.addEventListener("click", addText);
}

I have viewed various sources of help online including from this site however I simply cannot get any to work correctly. Thank you in advance.


Solution

  • Sure, it should be easy to locate the added <p> tag relative to the remove button that gets clicked.

    function removeText() {
      var weekParent = this.parentNode.parentNode;
      var item = weekParent.querySelector("p");
      weekParent.removeChild(item);
    }
    

    If there is more than 1 <p> tag inside the weekParent you will need a more specific querySelector.