Search code examples
javascriptbootstrap-5bootstrap5-modal

Is there a simpler way to set modal-body text by classname


I am using Bootstrap 5.1.3 with Pure Vanilla JavaScript and I am able to set the .modal-body content using below:

function showBSModal(modalid, inputid) {
    var myModal = new bootstrap.Modal(document.getElementById(modalid), {});
    var theValue = document.getElementById(inputid).value;
    const parent = document.getElementById(modalid);
    parent.querySelector(".modal-body").innerHTML = "Successfully Delete Uesr with ID: " + theValue;
    myModal.show();
};

Here I am passing modalid and my input box's id (inputid) dynamically and getting the desired output.

enter image description here

I tried myModal.querySelector instead of parent.querySelector but that did not work as myModal.querySelector is not accepted by the browser.

Question: Any there a better say to achieve above?


Solution

  • myModal is a modal object and not an HTML element. Let's load the HTML element, store it in a variable and use that instead.

    function showBSModal(modalid, inputid) {
        let context = document.getElementById(modalid);
        var myModal = new bootstrap.Modal(context, {});
        var theValue = document.getElementById(inputid).value;
        context.querySelector(".modal-body").innerHTML = "Successfully Delete Uesr with ID: " + theValue;
        myModal.show();
    };