HTML · The document layer
How does the dialog element work?
Short answer
The dialog element is a native modal or modeless dialog. showModal() traps focus and makes the rest of the page inert; close() dismisses it, and form method=dialog returns a value.
The dialog element gives you a styled container plus native modal behaviour. With showModal(), the browser moves focus into the dialog, makes the rest of the document inert and supports Escape to close.
<dialog id="confirm">
<form method="dialog">
<h2>Delete this item?</h2>
<p>This action cannot be undone.</p>
<button value="cancel">Cancel</button>
<button value="confirm">Delete</button>
</form>
</dialog>
<script>
const dialog = document.querySelector("#confirm");
dialog.showModal();
</script>What you get and what you still need
- showModal() opens a modal and makes background content inert
- show() opens a modeless dialog that does not block the page
- close() closes it, and the close event fires
- Escape closes a modal dialog by default
- form method=dialog closes the dialog and sets returnValue to the button value
Give the dialog an accessible name, usually with aria-labelledby pointing at its heading. The dialog role is implicit, so you do not need to add role=dialog. Manage focus deliberately, especially when you open or close it programmatically.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between show() and showModal()?
- 2How does form method=dialog work?
- 3Does Escape close a dialog automatically?
- 4How do you give a dialog an accessible name?
Say it in the interview
The dialog element is a native container for modal or modeless dialogs. showModal opens it as a modal, moves focus inside, makes the rest of the page inert and lets Escape close it. I use show for a non-blocking dialog. I give it an accessible name with aria-labelledby, and if I use a form with method=dialog, the button value becomes the return value when it closes. I still manage focus when opening and closing programmatically.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live HTML mock interview and get scored feedback on depth, clarity and confidence.