Utilizing the Bootstrap 5 "collapse" feature, I am implementing it using the data attributes method. Everything works perfectly as intended - I can simply click the button to collapse or expand the collapsible items.
According to the documentation, I should be able to manually toggle the state with the following code:
let element = document.querySelector('#my-collapse');
bootstrap.Collapse.getInstance(element).toggle();
Unfortunately, this approach fails because the getInstance
method returns null
.
Oddly enough, if I first click on the collapse button and then execute the code, it miraculously works.
Is there a way to ensure that the code functions correctly without having to "prime" the collapse component beforehand?