tooltip.js安装后使用求助:非Bootstrap环境下如何正确调用?
Hey there! I totally get where you're coming from—tooltip.js docs can feel a bit opaque if you're not super familiar with DOM APIs, especially without Bootstrap to lean on. Let's fix that error and get your tooltips working step by step.
The Root Cause of Your Error
That TypeError: reference.addEventListener is not a function happens because you're passing a CSS selector string (like '#my-element') to the Tooltip constructor, but it expects a real DOM element object instead. Strings don't have event listener methods—only actual elements do.
Step-by-Step Implementation
Let's walk through the correct way to set this up with webpack:
Confirm Your Import
First, make sure you're importing tooltip.js correctly (you said you already did this, but just to double-check):import Tooltip from 'tooltip.js';Grab the DOM Element
Use methods likedocument.querySelector()ordocument.getElementById()to get the actual element you want to attach the tooltip to. For example:// Get element by ID const referenceElement = document.getElementById('tooltip-trigger'); // OR get element by class/selector // const referenceElement = document.querySelector('.tooltip-button');Initialize the Tooltip
Pass the DOM element as the first argument, then add your configuration options (like tooltip text, placement, etc.):const myTooltip = new Tooltip(referenceElement, { title: 'Hello! This is my tooltip content', placement: 'bottom', // Options: top, bottom, left, right trigger: 'click', // Trigger on click instead of hover (default is 'hover focus') delay: 300 // Add a 300ms delay before showing/hiding });
Bonus: Dynamic Elements & DOM Readiness
If your trigger element is added to the page dynamically (e.g., loaded via AJAX), or if you're initializing the tooltip before the DOM is fully loaded, wrap your code in a DOMContentLoaded listener to ensure the element exists:
document.addEventListener('DOMContentLoaded', () => { const referenceElement = document.getElementById('tooltip-trigger'); const myTooltip = new Tooltip(referenceElement, { title: 'Loaded after DOM is ready!' }); });
Customizing Tooltip Content
Want to use HTML instead of plain text? Enable the html option and pass HTML as your title:
const myTooltip = new Tooltip(referenceElement, { title: '<strong>Important!</strong> This is bold tooltip text', html: true });
内容的提问来源于stack exchange,提问作者KSPR

