how to display 1 data without looping using insertAdjacentHTML

113 views Asked by At

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>

1

There are 1 answers

1
Silviu Burcea On BEST ANSWER

If you want only one adjacent HTML added, you need to disable the onclick listener (or replace/remove existing HTML with the new one). You can make a click listener to fire once by adding an extra parameter when setting it, { once: true }, like below:

var btn = document.getElementById("btnClick");
btn.addEventListener("click", function (e) {
    e.preventDefault();
    var string= "";
    string += '<p>FINISH</p>';
    document.querySelector(".test").insertAdjacentHTML("afterend", string);
}, { once: true });
<button id="btnClick">CLICK</button>
<div class="test"></div>

For replacing the element you've added, you can use nextElementSibling to replace it. I'm assuming there is nothing after .test element initially, you might want to test that first so you don't accidentally remove elements you don't want to:

var btn = document.getElementById("btnClick");
btn.addEventListener("click", function (e) {
    e.preventDefault();
    var string= "";
    string += '<p>FINISH</p>';
    document.querySelector(".test").nextElementSibling.remove();
    document.querySelector(".test").insertAdjacentHTML("afterend", string);
});
<button id="btnClick">CLICK</button>
<div class="test"></div>