Duplicate element in DOM with JS

Asked

Viewed 81 times

1

I need to add a <li> via Javascript, but when added, from the second addition, it starts to duplicate, triple and so on, I need you 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>

1 answer

3


Since you are declaring the method to be executed directly on the button, it makes no sense that this adds an eventListener to the click event.

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

And in 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 reported behavior.

Simply remove the snippet where you add the system.

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>

Browser other questions tagged

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