Home > front end >  How to check a element is appended or not in JavaScript
How to check a element is appended or not in JavaScript

Time:09-26

I have a JavaScript function which append an p tag with class myPara .

I want to check if till now element is appended or not :

  • if appended then stop next appending
  • if not appended then append the p tag

I have tried some SO questions all are about jQuery, can tell in JavaScript

How to check for the existence of an element after append?

How can I check if append element already exists? [duplicate]

function appendPara() {
  let para = document.createElement("p");
  para.className = "myPara";
  var textnode = document.createTextNode("Dummy is my brother");
  para.appendChild(textnode);
  document.getElementById("containPara").appendChild(para);
}

function checkPara() {
  //if (more than 1 length of class ="dummyPara" present)
    //appendPara() will not append next element
//} else {
  //appending will take place by appendPara()
//}
}
<div id="containPara">
  <p class="dummyPara">I am dummy plz don't remove me. You get a chance on next appendings but leave the 1st on he is my brother from another mother</p>
</div>
<button onclick="appendPara()">Append p</button>
<button onclick="checkPara()">Check appending</button>

Thanks a lot in advance

CodePudding user response:

You don't need checkPara, at all. Just create para outside appendPara, which allow checking inside your function that adds it.

const para = document.createElement("p");
para.className = "myPara";
const textnode = document.createTextNode("Dummy is my brother");
para.appendChild(textnode);
const containPara = document.getElementById("containPara");

function appendPara() {
  if (![...containPara.children].includes(para))
    containPara.appendChild(para);
}
<div id="containPara">
  <p class="dummyPara">I am dummy plz don't remove me. You get a chance on next appendings but leave the 1st on he is my brother from another mother</p>
</div>
<button onclick="appendPara()">Append p</button>

[...containPara.children]

spreads the element childnodes into an array, which allows using array methods like includes on it.

CodePudding user response:

Is this useful for you ?

document.getElementById("appendP").addEventListener("click",function(){

  let para = document.createElement("p");
  para.className = "myPara";
  var textnode = document.createTextNode("Dummy is my brother");
  para.appendChild(textnode);
  document.getElementById("containPara").appendChild(para);
    
},{once:true})
    <div id="containPara">
  <p class="dummyPara">I am dummy plz don't remove me. You get a chance on next appendings but leave the 1st on he is my brother from another mother</p>
</div>
<button id="appendP">Append p</button>

  • Related