How to delete the last div added by DOM?

Asked

Viewed 156 times

0

I’m making 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 note.

<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>

1 answer

1

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

You can solve your problem by using class (Attribute class) to id index to take the last element inserted on 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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.