Duplicate element in DOM with JS

1

I need to add <li> via JavaScript, but when added, from the second addition, it starts to duplicate, triple, and so on, I need to add only 1 element per click.

var btn = document.querySelector("#btn");
var ps = document.querySelector(".pessoinhas");
var psL = document.querySelector("#pessoinhasLi");

function add() {

  btn.addEventListener("click", function(event) {

    event.preventDefault();
    var campo = document.getElementById("campoUL");
    var input = document.createElement("li");
    campo.appendChild(input).innerHTML = ps.value;

  });
}
<!DOCTYPE html>
<html>

<head>
  <title>Teste</title>
</head>

<body>
  <p>Tarefa</p>
  <div>
    <ul id="campoUL"></ul>
  </div>
  <div>
    <button id="btn" onclick="add()">Adicionar</button>
    <input type="text" class="pessoinhas">
  </div>
</body>

</html>
    
asked by anonymous 22.06.2018 / 16:41

1 answer

3

As you are declaring the method to be run directly on the button, it does not make sense for it to add an eventListener to the click event.

 <button id="btn" onclick="add()">Adicionar</button>

And no javascript:

function add() {

  btn.addEventListener("click", function(event) {
    // ...
  }
}

So every time you click the button it will add all the behavior once again and this explains the behavior reported.

Simply remove the snippet where you add the listener.

var btn = document.querySelector("#btn");
var ps = document.querySelector(".pessoinhas");
var psL = document.querySelector("#pessoinhasLi");

function add() {
    event.preventDefault();
    var campo = document.getElementById("campoUL");
    var input = document.createElement("li");
    campo.appendChild(input).innerHTML = ps.value;
}
<!DOCTYPE html>
<html>

<head>
  <title>Teste</title>
</head>

<body>
  <p>Tarefa</p>
  <div>
    <ul id="campoUL"></ul>
  </div>
  <div>
    <button id="btn" onclick="add()">Adicionar</button>
    <input type="text" class="pessoinhas">
  </div>
</body>

</html>
    
22.06.2018 / 16:46