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

纯JS实现超出9个filterDiv后隐藏及加载更多功能

Solution to Hide Extra .filterDiv Elements and Add Load More Functionality

Got it, let's fix this up so you can hide the 10th+ .filterDiv elements and toggle them with the Load More button. Here's a step-by-step breakdown:

Step 1: Hide Extra Elements on Initial Load

First, we'll grab all .filterDiv elements, check if there are more than 9, and hide everything starting from the 10th one (remember, JavaScript uses 0-based indexing, so the 10th element is at index 9).

Update your existing code to this:

const filterDivs = document.querySelectorAll('.filterDiv');
const htCount = filterDivs.length;
const loadMoreBtn = document.querySelector('#loadMore');

// Hide elements beyond the 9th one if count exceeds 9
if (htCount > 9) {
  // Loop from index 9 (10th element) to the last one
  for (let i = 9; i < htCount; i++) {
    filterDivs[i].classList.add('hide');
  }
  // Show the Load More button
  loadMoreBtn.classList.add('show');
}

Don't forget to add CSS for the .hide class to actually hide the elements:

.hide {
  display: none;
}

Step 2: Add Load More Button Functionality

Now we need to make the button show the hidden elements. You can choose between two common approaches:

Option 1: Show All Hidden Elements at Once

This will reveal every hidden .filterDiv when the button is clicked, then hide the button itself:

loadMoreBtn.addEventListener('click', () => {
  // Remove the hide class from all filterDivs
  filterDivs.forEach(div => div.classList.remove('hide'));
  // Hide the Load More button since there's nothing left to load
  loadMoreBtn.classList.remove('show');
});

Option 2: Load Elements in Batches (e.g., 3 at a Time)

If you prefer a gradual load (better for large lists), this will show 3 more elements each time the button is clicked, and hide the button once everything is visible:

// Track how many elements are currently visible (starts at 9)
let currentVisibleCount = 9;

loadMoreBtn.addEventListener('click', () => {
  // Calculate how many more elements to show (max 3, or whatever's left)
  const nextVisibleCount = Math.min(currentVisibleCount + 3, htCount);
  
  // Show the next batch of elements
  for (let i = currentVisibleCount; i < nextVisibleCount; i++) {
    filterDivs[i].classList.remove('hide');
  }
  
  // Update the visible count
  currentVisibleCount = nextVisibleCount;
  
  // Hide the button if all elements are now visible
  if (currentVisibleCount >= htCount) {
    loadMoreBtn.classList.remove('show');
  }
});

That's it! This setup will handle hiding extra elements on page load and letting users reveal them with the Load More button.

内容的提问来源于stack exchange,提问作者user4889134

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:30:28