I want to use dialog element while update the the DOM.
When I try to update the DOM and open the dialog with the button containing Id="openDialogBtn". The dialog box is working fine(able to open), but the button with id="closeDialogBtn" isnot working while trying to close the dialog box. Here's my code
const openDialogBtn = document.getElementById("openDialogBtn");
const closeDialogBtn = document.getElementById("closeDialogBtn");
const dialogContainer = document.getElementById("dialogContainer");
openDialogBtn.addEventListener("click", () => {
dialogContainer.innerHTML += `<p>Hello World</p>`
dialogContainer.showModal();
})
closeDialogBtn.addEventListener("click", () => {
dialogContainer.close();
console.log("dialog closed")
})
<button id="openDialogBtn">Open Dialog</button>
<dialog id="dialogContainer">
<button id="closeDialogBtn">Close Dialog</button>
<p>Dialog Content</p>
</dialog>
As @CBroe Commented your destroying your dialogs content and recreating them detaching the close buttons event. This method keeps your close button intact since we are only targeting a tag inside the Dialog.