HTMLDialogElement: close() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2022.
Theclose() method of theHTMLDialogElement interface closes the<dialog>.An optional string may be passed as an argument, updating thereturnValue of the dialog.
Theclose event is fired after the dialog has closed.Unlike when callingHTMLDialogElement.requestClose(), the close operation cannot be cancelled.
In this article
Syntax
close()close(returnValue)Parameters
returnValueOptionalA string that replaces the existing value of
HTMLDialogElement.returnValue.
Return value
None (undefined).
Examples
>Closing a dialog
The following example shows a button that, when clicked, opens a<dialog> via theshowModal() method.From there you can click the eitherClose button to close the dialog (via theclose() method).
TheClose button closes the dialog without areturnValue, while theClose w/ return value button closes the dialog with areturnValue.
HTML
<dialog> <button type="button">Close</button> <button type="button">Close w/ return value</button></dialog><button>Open dialog</button><pre></pre>#log { height: 170px; overflow: scroll; padding: 0.5rem; border: 1px solid black;}JavaScript
const logElement = document.getElementById("log");function log(text) { logElement.innerText = `${logElement.innerText}${text}\n`; logElement.scrollTop = logElement.scrollHeight;}const dialog = document.getElementById("dialog");const openButton = document.getElementById("open");const closeButton = document.getElementById("close");const closeWithValueButton = document.getElementById("close-w-value");// Update button opens a modal dialogopenButton.addEventListener("click", () => { // Reset the return value dialog.returnValue = ""; // Show the dialog dialog.showModal();});// Close button closes the dialog boxcloseButton.addEventListener("click", () => { dialog.close();});// Close button closes the dialog box with a return valuecloseWithValueButton.addEventListener("click", () => { dialog.close(`Closed at ${new Date().toLocaleTimeString()}`);});// Form close button closes the dialog boxdialog.addEventListener("close", () => { log(`Dialog closed. Return value: "${dialog.returnValue}"`);});Note:
You know you can also automatically close a<dialog> by submitting a<form> element with amethod="dialog" attribute.
Result
Specifications
| Specification |
|---|
| HTML> # dom-dialog-close-dev> |
Browser compatibility
See also
- HTML
<dialog>element - The
closeevent HTMLDialogElement.requestClose()