Saqlain Ishtiaq
Saqlain Ishtiaq

Reputation: 73

Stop appending same element to the node

I am appending element on a node. I am stuck in a situation that on every click event the same element get append to the parent.

How can I stop preventing the element to append again and again and add just once on the first click.

   document.getElementsByClassName("btn")[0].onclick = function(e) {
   e.preventDefault();
   var div = document.createElement("div");
   div.innerHTML="error";
   document.getElementsByClassName("errors")[0].appendChild(div);
}
div { border: 1px solid black }
<button class="btn" type="button">Click</button>
<div class="errors">Errors:</div>

Upvotes: 0

Views: 293

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386728

After using the event, you could assign an empty function to the event.

document.getElementsByClassName("btn")[0].onclick = function(e) {
    var div = document.createElement("div");
    e.preventDefault();
    div.innerHTML = 'test';
    document.getElementsByClassName("errors")[0].appendChild(div);
    document.getElementsByClassName("btn")[0].onclick = function () {};
}
<button class="btn">button</button>
<div class="errors"></div>

Upvotes: 1

Renzo Calla
Renzo Calla

Reputation: 7706

You an put a conditional in your click event... like this one, carefull this is asking if it has a a child, you might want to set a more specific conditional....

var div = document.createElement("div");
document.getElementsByClassName("btn")[0].onclick = function(e) {
   e.preventDefault();
   if (document.getElementsByClassName("errors")[0].firstChild) {
       document.getElementsByClassName("errors")[0].appendChild(div);
   }  
}

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68413

You can check if a div (or any other selector) is already there or not.

var errorEl = document.getElementsByClassName("errors")[0];
var doesDivExist = !!errorEl.querySelector( "div" );
if ( !doesDivExist )
{
   errorEl.appendChild(div);
}

Demo

var div = document.createElement("div");
div.innerHTML = "error";
document.getElementsByClassName("btn")[0].onclick = function(e) {
  e.preventDefault();
  var errorEl = document.getElementsByClassName("errors")[0];
  var doesDivExist = !!errorEl.querySelector("div");
  if (!doesDivExist) {
    errorEl.appendChild(div);
  }
}
div {
  border: 1px solid black
}
<button class="btn" type="button">Click</button>
<div class="errors">Errors:</div>

Upvotes: 0

Related Questions