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
ptag
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
const parent = document.getElementById("containPara"); if (!parent.querySelector(".myPara")) { /* ...it's not there, create and append it...*/}Elementinterface hasquerySelector, which lets you look for elements within the original element using any CSS selector.CheckPara()button onclick but function name ischeckPara().