Skip to content
Advertisement

How can I save buttons in variable, created by Element.insertAdjacentHTML() method?

as I said in title I have problem with HTML elements created with Element.insertAdjacentHTML() method, I’m trying about an hour to solve this but can’t. I have button that create new HTML elements, couple of that elements is new buttons with same class or id, it’s no matter, that I need to catch in some variable and than again use for event listener, for some reason the class or id for these new created button doesn’t exist, is there any way to catch it and use it later, I need Vanila Javascript?

There is over 500 lines of code, this is only for mentioned method

btnClaim.addEventListener("click", () => {
    rewardCurrent.style.display = "none";
    claimedRewards.push(currentReward);
    rewardsList.innerHTML = ``;

    claimedRewards.forEach(function (rew, i) {
      const html = `
    <div class="reward" id="${i}">
      <div class="img-text-cont">
        <img src="${rew.imgUrl}" alt="">
        <div class="text-cont">
          <p class="claimed-reward-title">${rew.title}</p>
          <p class="claimed-reward-price">$${rew.price}</p>
        </div>
      </div>
      <div class="claimed-rewards-action">
        <button id="btn-sell2">Sell</button>
        <button id="btn-ship">Ship</button>
      </div>
    </div>
      `;

      rewardsList.insertAdjacentHTML("afterbegin", html);

I need that btn-sell2 and btn-ship buttons in variables.

Advertisement

Answer

your element is going to be created and doesn’t exist at the time page loads, so js addeventlistener will throw an error. to solve you have 2 ways.

1- use parent node that element will be created inside. addevenlistener to parent and use

parent.addeventlistener( event, function (event){
    if(event.target.classList.contains("childClass") {}
}

2- give addeventlistener when creating the element :

function createElement () {
  const elem = -craete elemnt-
  elem.addeventlistener(event, function);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement