Broken Javascript Code

I'm trying to create a website where three things happen, but I am stuck.

(1) When the button “ADD” button is clicked it will create a new paragraph and add it to the output. The contents of the paragraph should come from the text area that is below the [ADD] button.

(2) If the “delete” button is pressed I need to delete the first paragraph in the div.

(3) If the user tries to delete when there are no paragraphs, create an “alert" that says:"No Paragraphs to delete".

I got my JS to put each paragraph into the div, but I'm not really sure how to delete it... Any help would be much appreciated.

window.onload = function() {
  var button = document.getElementById("add");
  button.onclick = insertItem;

function insertItem() {
  var added = document.getElementById("output");
  var textToAdd = document.getElementById("input");
  if (textToAdd.value != "") {
    var newp = document.createElement("p");
    newp.innerHTML = textToAdd.value;

var deletebutton = document.getElementsByTagName("delete");
deletebutton.onclick = deleteItem;

function deleteItem() {
  var output = document.getElementById("output");
  var pars = output.getElementsByTagName("p");
  if (pars.length > 0) {
#output {
  border: blue 5px solid;
  padding: 10px;
  margin-bottom: 10px;
  margin-top: 10px;
  width: 50%;

#output p {
  padding: 10px;
  border: black 1px dashed;

  <script src="" type="text/javascript"></script>
  <script src="task3.js"></script>

  <h2> TASK 3 - Creating, Appending and Deleting Nodes in the DOM Tree </h2>
  <p> Type in text below, click add to add as paragraph. <button id="add"> Add </button> </p>
  <textarea id="input" rows="10" cols="60">
  <button id="delete">Delete Last Paragraph</button>
  <h2> Added Paragraphs </h2>
  <div id="output">


1 answer

  • answered 2017-11-14 23:43 ThatBrianDude

    1. You're fetching the delete button wrong. You're using getElementsByTagName instead of by id.

    2. When deleting, you will probably delete the first <p> you have in your markup that doesnt belong to your output. To fix this you could simply fetch all children of your output div and remove the first one:

      function deleteItem() {
          let output = document.getElementById('output')
          if (output.hasChildNodes()) {
              let outputs = output.childNodes