Bootstrap5 Modal Uncaught TypeError: 'querySelector' called on an object that does not implement interface Element

Viewed 3873

i want to use a modal so like in the docu i trie it in this way

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
  Launch static backdrop modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

On click at the button i get this error "Uncaught TypeError: 'querySelector' called on an object that does not implement interface Element"

What i do wrong?

4 Answers

data-bs-target and your modal's id should be identical, changing data-bs-target value to #exampleModal should fix your problem.

Removing the "data-bs-target="#staticBackdrop" Part of the button solved the problem. I dont know what or why it came up, but now it works for me.

I was getting this error in Bootstrap 5 when I had data-bs-target set to the right modal ID, but the modal itself wasn't formatted correctly. To work properly the modal parent class has to include at least a modal-dialog child element.

I removed "data-bs-target" and worked for me, my code

Button, you have to assign it an id:

<!-- Button trigger modal -->
  <button id="test" type="button" class="btn btn-primary">
    Launch demo modal
  </button>

Modal:

<!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>

Javascript:

var myModal = new bootstrap.Modal(document.getElementById("test"));

myModal.toggle();
Related