Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Get Bootstrap Modal Instance Using JavaScript</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script> <script> document.addEventListener("DOMContentLoaded", function() { var btn = document.getElementById("myBtn"); btn.addEventListener("click", function() { var myModal = document.getElementById("myModal"); var modal = bootstrap.Modal.getInstance(myModal); console.log(modal); }); }); </script> <style> #myBtn{ z-index: 9999; /* to show button on top of backdrop */ } </style> </head> <body> <div class="m-4"> <div class="text-center"> <!-- Button HTML (to Trigger Modal) --> <button type="button" class="btn btn-lg btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">Launch Modal</button> <p class="mt-4">First launch modal, then press the "Get Modal Instance" button to get the modal instance associated with a DOM element.</p> <p>Press Ctrl+Shift+J (Windows / Linux) or Cmd+Opt+J (Mac) to open the browser console panel.</p> <!-- Button HTML (to Get Modal Instance) --> <button type="button" id="myBtn" class="btn btn-lg btn-warning fixed-bottom mx-auto w-50 mb-4">Get Modal Instance</button> </div> <!-- Modal HTML --> <div id="myModal" class="modal fade" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Confirmation</h5> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> <p>Do you want to save changes to this document before closing?</p> <p class="text-secondary"><small>If you don't save, your changes will be lost.</small></p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> </body> </html>