I'm having a problem. why is the insertAdjacentHTML("afterend") output looping?, i want to display 1 only, not repeated.
var btn = document.getElementById("btnClick");
btn.addEventListener("click", function (e) {
e.preventDefault();
var string= "";
string += '<p>FINISH</p>';
document.querySelector(".test").insertAdjacentHTML("afterend", string);
});
<button id="btnClick">CLICK</button>
<div class="test"></div>
If you want only one adjacent HTML added, you need to disable the
onclicklistener (or replace/remove existing HTML with the new one). You can make aclicklistener to fire once by adding an extra parameter when setting it,{ once: true }, like below:For replacing the element you've added, you can use
nextElementSiblingto replace it. I'm assuming there is nothing after.testelement initially, you might want to test that first so you don't accidentally remove elements you don't want to: