'How to open a modal for a particular ID in vanilla JavaScript
In Bootstrap, to open a pop-up window, you do this, using jQuery:
$('#edit_modal').modal();
You call the modal function for this ID. What is the equivalent in vanilla JavaScript? I tried:
document.getElementById("edit_modal").modal();
and I get:
document.getElementById(...).modal is not a function
What am I missing? How can I call a function for a particular ID?
Thanks.
Solution 1:[1]
As others have indicated in the comments, .modal() is a method specific to Bootstrap/jQuery, which is why you can't call it via "regular" JavaScript.
However, for standard DOM methods, your syntax would work. For example,
document.getElementById("edit_modal").focus();
or
document.getElementById("edit_modal").blur();
would both work fine with vanilla JavaScript.
Solution 2:[2]
You could use several ways, try :
document.getElementById('elem_id')
document.getElementById('elem_id')[0]
document.querySelector('#elem_id')
document.querySelectorAll('#elem_id')[0]
Hope this helps.
Solution 3:[3]
Since Materialize CSS now is not JQuery-dependent, the answer to your question is in their website:
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.modal');
var instances = M.Modal.init(elems, options);
});
``````
This is the link to their website: https://materializecss.com/modals.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | freginold |
| Solution 2 | Zakaria Acharki |
| Solution 3 | Gianni Fontanot |
