How do I delete the last div added by the DOM?

0

I'm doing a notes webapp, I used DOM to add notes and remove, but when I remove it, it removes the first note and not the last one.

<script async>
        function novaNota() {
            var div = document.createElement("div");
            div.id = "div";
            div.style = "background-color: coral; padding: 10px; box-shadow: 3px 3px 3px silver; margin-left: 25px; margin-right: 25px;";
            document.body.appendChild(div);

            var input = document.createElement("input");
            input.id = "input";
            input.type = "checkbox";
            input.style = "width: 25px; height: 25px; margin-left: 25%;";
            div.appendChild(input);

            var nome = prompt("Adicionar:");
            var p = document.createElement(p);
            p.textContent = nome;
            p.style = "font-size: 20px; margin-left: 5%";
            div.appendChild(p);
        }
        function removerNota() {
            var div = document.getElementById("div");
            document.body.removeChild(div);
        }
    </script>
    
asked by anonymous 06.11.2016 / 00:45

1 answer

1

The error that occurs in your code is due to you are using the identifier (Attribute ID) of elements created with the same name, and the ID of an element must be joined, and can not be used in other elements, which is what happens in your code, however, when that happens the element that will be returned by the function getElementById will be the first element of the page with the name of the last ID of the function call.

You can solve your problem by using class (attribute class) at the bottom of id to get the last element inserted in the page, as in the example below based on your code:

function novaNota() {
  var div = document.createElement("div");
  div.id = "div";
  div.className = "div";
  div.style = "background-color: coral; padding: 10px; box-shadow: 3px 3px 3px silver; margin-left: 25px; margin-right: 25px;";
  document.body.appendChild(div);

  var input = document.createElement("input");
  input.id = "input";
  input.type = "checkbox";
  input.style = "width: 25px; height: 25px; margin-left: 25%;";
  div.appendChild(input);

  var nome = prompt("Adicionar:");
  var p = document.createElement(p);
  p.textContent = nome;
  p.style = "font-size: 20px; margin-left: 5%";
  div.appendChild(p);
}
function removerNota() {
  var allDiv = document.getElementsByClassName("div"),
  		div = allDiv[allDiv.length - 1];
  document.body.removeChild(div);
}

novaNota()
novaNota()
removerNota();
    
06.11.2016 / 01:16