3

First I'll state that I have searched and found many other questions that are similar to this, but all that I have found use either jquery, bootstrap, react, etc..., while I simply want a simple HTML/CSS/JS solution.

Change react-modal data dynamically launch modal with dynamically added button Modal Popup on Dynamic Button

I took W3school's code and made a few adjustments to test my theory, and the results lead me to believe that a dynamically created button cannot change existing elements in the html. https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal

I dynamically added a simple button to the code and have it on jsfiddle.

document.createElement("button");
document.body.innerHTML += "<button onclick = show()>xxxxx</button>";

function show() {
    alert("it went here");
    modal.style.display = "block";
}

https://jsfiddle.net/IWannaDance/sg4nb6e5/1/

I knew to javascript and I'm not sure why I'm unable to change the modal with my button. Other answers for the similar questions said something of an event listener and I'm not sure how its related to this. An explanation and workaround for this would be greatly appreciated.

Edit: This is just an example I used to test, while my actual javascript code uses a for loop to create identically formatted divs, and each div has a dynamically added button, all added with appendChild. If I create a div in my html document called modal, and I try to change its attributes in javascript, it doesn't seem to work. However, If I create a new modal with the click of the button, it does show. I guess that will be my temporary workaround until I can find a better way.

1 Answers1

0

Adding an element like this document.body.innerHTML += rewrites the whole page and destroys the reference to the "modal" element

It will work if you use appendChild instead to add the button element

var btn = document.createElement("button");
btn.textContent = "xxxxx";
btn.onclick = show;
document.body.appendChild(btn);

function show() {
  console.log("it went here");
  modal.style.display = "block";
}

JSFiddle

aabuhijleh
  • 2,214
  • 9
  • 25
  • Hey your code snippet works, but if I change the second line back to btn.innerHTML it also works so I guess the main part is the appendChild part. In my own code, that is the format I have. I used a for loop to dynamically add a number of divs, and each div contains a button that is added with appendChild. Clicking on any of the buttons is supposed to show the modal, but none of those buttons work. This is the part I am confused about. – IWannaDance Mar 08 '21 at 21:01
  • Without showing your code, I can't know what's going wrong for you – aabuhijleh Mar 09 '21 at 04:40