So I have an index.html that I cant edit. Only thing I can use is a javascript file that is linked to that index file. Modal is supposed to be created through javascript (through createElement method).
This is where I have a problem because I can't append that modal to document and I have a problem showing it directly from a function in the script.
Is this even possible to do in vanilla js? I know there are solutions with jquery but I am interested in the vanilla approach.
This is a test with a button so I would be sure it works, then I would code it to run on ready:
<button onclick="Popup()" role='button'>
Show Alert
</button>
<script type="text/javascript">
function Popup() {
var myDialog = document.createElement("dialog");
var text = document.createTextNode("This is a dialog window");
myDialog.appendChild(text);
myDialog.showModal();
}
</script>
And here is the error:
Uncaught DOMException: Failed to execute 'showModal' on 'HTMLDialogElement': The element is not in a Document.
So I have an index.html that I cant edit. Only thing I can use is a javascript file that is linked to that index file. Modal is supposed to be created through javascript (through createElement method).
This is where I have a problem because I can't append that modal to document and I have a problem showing it directly from a function in the script.
Is this even possible to do in vanilla js? I know there are solutions with jquery but I am interested in the vanilla approach.
This is a test with a button so I would be sure it works, then I would code it to run on ready:
<button onclick="Popup()" role='button'>
Show Alert
</button>
<script type="text/javascript">
function Popup() {
var myDialog = document.createElement("dialog");
var text = document.createTextNode("This is a dialog window");
myDialog.appendChild(text);
myDialog.showModal();
}
</script>
And here is the error:
Share Improve this question edited Jan 25, 2018 at 14:30 Sushmita 951 silver badge8 bronze badges asked Jan 25, 2018 at 13:55 AndrejAndrej 331 silver badge5 bronze badges 1Uncaught DOMException: Failed to execute 'showModal' on 'HTMLDialogElement': The element is not in a Document.
-
1
You will need to append the element
myDialog
to the document somewhere. – phuzi Commented Jan 25, 2018 at 13:57
2 Answers
Reset to default 3Append the dialog element to the body using document.body.appendChild(myDialog)
function Popup() {
var myDialog = document.createElement("dialog");
document.body.appendChild(myDialog)
var text = document.createTextNode("This is a dialog window");
myDialog.appendChild(text);
myDialog.showModal();
}
<button onclick="Popup()" role='button'>
Show Alert
</button>
No there is no "dialog" element that has that functionality. You'll have to create a regular element append it to the document and then have css to position it.