Bootstrap5跨区域标签页点击触发Uncaught TypeError错误的原因及解决方法
Got it, let's tackle two problems here: that annoying Uncaught TypeError and the conflict between your top and bottom tab groups.
Why the Error Happens
Your code defines two separate collections:
linkItem: All elements with class.nav-item__linknavLink: All elements with class.nav-link
In the second loop, you iterate over the length of navLink, but try to access linkItem[j] for each index j. If navLink has more elements than linkItem, once j exceeds the last index of linkItem, linkItem[j] becomes undefined—and you can't call .classList on something that doesn't exist. That's exactly what's throwing the error.
Solution: Unified Tab Handling
Instead of treating top and bottom tabs as separate groups, we'll handle all tab triggers together. This ensures we don't run into index mismatches, and automatically clears active states across all tabs when any tab is clicked.
Here's the refactored code that fixes both issues:
// Grab ALL tab trigger elements (top and bottom combined) const allTabTriggers = document.querySelectorAll('.nav-item__link, .nav-link'); // Grab all tab content panes const tabPanes = document.querySelectorAll('.tab-pane'); // Add click event to each trigger allTabTriggers.forEach(trigger => { trigger.addEventListener('click', function(e) { e.preventDefault(); // Step 1: Remove active class from ALL tab triggers (top + bottom) allTabTriggers.forEach(tab => tab.classList.remove('active')); // Step 2: Add active class to the clicked trigger this.classList.add('active'); // Step 3: Get the target pane using Bootstrap's standard attributes const targetSelector = this.getAttribute('data-bs-target') || this.getAttribute('href'); // Step 4: Hide all panes by removing active/show classes tabPanes.forEach(pane => pane.classList.remove('active', 'show')); // Step 5: Show the target pane const targetPane = document.querySelector(targetSelector); if (targetPane) { targetPane.classList.add('active', 'show'); } }); });
Key Notes for This Fix
- Unified Trigger Collection: By combining
.nav-item__linkand.nav-linkinto one set, we eliminate index mismatches entirely. - Bootstrap Compatibility: This uses Bootstrap's native
data-bs-targetorhrefattributes to link triggers to their panes. Make sure your HTML follows this pattern:<!-- Example top tab trigger --> <a href="#tab-content-1" class="nav-item__link">Top Tab 1</a> <!-- Example bottom tab trigger --> <a data-bs-target="#tab-content-2" class="nav-link">Bottom Tab 2</a> <!-- Corresponding pane --> <div class="tab-pane" id="tab-content-1">Content for Top Tab 1</div> - Clean State Management: Every click resets all tab active states before setting the new one—so no more overlapping active classes between top and bottom tabs.
内容的提问来源于stack exchange,提问作者nikitasalnikov

