You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

tooltip.js安装后使用求助:非Bootstrap环境下如何正确调用?

How to Use tooltip.js Without Bootstrap (Fixing the "addEventListener is not a function" Error)

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:

  1. 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';
    
  2. Grab the DOM Element
    Use methods like document.querySelector() or document.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');
    
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:20:22