简体   繁体   中英

How to initialize Tooltips in Bootstrap 4 with pure JavaScript? No jQuery

I'm somehow stuck with this code:

$(function () {
  $('[data-toggle="tooltip"]').tooltip()
});

I'd like to change it to pure JavaScript. I'm not sure how to call the tooltip function, I already have some ideas like:

var tooltips = document.querySelectorAll("[data-toggle='tooltip']");
for(var i = 0; i < tooltips.length; i++){
   //this gives an error
   tooltips[i].tooltip();
}

I'm able to get all the tooltips, but I cannot initialize them. If I write something like this:

$(tooltips[i]).tooltip();

Then it works, but I want to remove the jQuery dependency since this is the only jQuery section that I have. Any idea? I've been searching and I cannot find anything useful.

This code worked for me. (Inspired by bootstrap 5)

var tooltipElementList = document.querySelectorAll('[data-toggle="tooltip"]');
for (var x = 0; x < tooltipElementList.length; x++) {
    new bootstrap.Tooltip(tooltipElementList[x]);
}

For the new Bootstrap 5 , this will be the new option without jQuery:

var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
})

More info: https://getbootstrap.com/docs/5.0/components/tooltips/

You can select all the elements with the data-toggle attribute you want like so:

    let tooltips = document.querySelectorAll('[data-toggle="tooltip"]')
    tooltips.forEach(tooltip => tooltip.tooltip())

And then loop through the resulting nodelist and then execute the method you want on each element.

However, this won't work for your particular use case, because the Bootstrap plugins rely on jQuery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM