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

使用Vanilla JS从数据对象填充HTML时仅显示首个元素的问题

Fixing "Only First Product Shows Up" in Vanilla JS

Hey there! Let's get your full product list displaying properly. This is a super common issue when working with loops and DOM manipulation in vanilla JS, so let's break down what's probably going wrong and how to fix it.

First, Let's Diagnose the Common Culprits

Most of the time, this happens because of one of these mistakes:

  • You're replacing the container's content each loop instead of adding to it (using = instead of += for innerHTML)
  • Your loop is terminating early (accidentally using return or break inside the loop)
  • You've got a bug in your loop condition (like using i <= 0 instead of i < products.length)
  • You're selecting the wrong DOM element (e.g., using querySelector on a container that only targets one element)

Let's Fix It with Working Code

First, let's start with a sample product array (you can swap this with your actual data):

const products = [
  { id: 1, name: "Organic Cotton T-Shirt", price: 29.99 },
  { id: 2, name: "High-Waisted Denim Jeans", price: 59.99 },
  { id: 3, name: "Eco-Friendly Sneakers", price: 89.99 },
  { id: 4, name: "Linen Button-Down", price: 49.99 }
];

Method 1: Accumulate HTML Strings (Simple for Small Datasets)

This is the easiest approach for small product lists. We build up a single HTML string first, then inject it all at once (better performance than updating the DOM every loop):

const productContainer = document.getElementById('product-container');
let productsHTML = '';

// Loop through every product
for (let i = 0; i < products.length; i++) {
  const product = products[i];
  // Add each product's HTML to our string
  productsHTML += `
    <div class="product">
      <h3>${product.name}</h3>
      <p>Price: $${product.price.toFixed(2)}</p>
    </div>
  `;
}

// Inject the full HTML into the container
productContainer.innerHTML = productsHTML;

Method 2: Create & Append DOM Elements (Better for Large Datasets)

If you have a lot of products, this method is more performant because it avoids repeatedly modifying the DOM:

const productContainer = document.getElementById('product-container');

// Use forEach to loop through products
products.forEach(product => {
  // Create a container for each product
  const productCard = document.createElement('div');
  productCard.classList.add('product');

  // Create product name element
  const nameEl = document.createElement('h3');
  nameEl.textContent = product.name;

  // Create product price element
  const priceEl = document.createElement('p');
  priceEl.textContent = `Price: $${product.price.toFixed(2)}`;

  // Add elements to the product card
  productCard.appendChild(nameEl);
  productCard.appendChild(priceEl);

  // Add the card to the main container
  productContainer.appendChild(productCard);
});

Quick Troubleshooting Steps

If you're still having issues:

  1. Check your array length: Run console.log(products.length) in your browser's dev tools to make sure your array has more than one item.
  2. Verify your loop condition: Double-check that your for loop uses i < products.length (not i <= 0 or another incorrect condition).
  3. Avoid overwriting content: If you're using innerHTML, make sure you're using += to add to the content, not = which replaces it.
  4. Confirm your container exists: Make sure document.getElementById('product-container') is actually finding your HTML element (it'll return null if it doesn't exist).

Here's a full working HTML example you can copy-paste to test:

<!DOCTYPE html>
<html>
<head>
  <title>My Product Store</title>
  <style>
    .product {
      border: 1px solid #ddd;
      padding: 15px;
      margin: 10px;
      width: 220px;
      border-radius: 4px;
    }
    h3 {
      margin: 0 0 10px 0;
    }
  </style>
</head>
<body>
  <div id="product-container"></div>

  <script>
    const products = [
      { id: 1, name: "Organic Cotton T-Shirt", price: 29.99 },
      { id: 2, name: "High-Waisted Denim Jeans", price: 59.99 },
      { id: 3, name: "Eco-Friendly Sneakers", price: 89.99 }
    ];

    const productContainer = document.getElementById('product-container');
    let productsHTML = '';

    for (let i = 0; i < products.length; i++) {
      const product = products[i];
      productsHTML += `
        <div class="product">
          <h3>${product.name}</h3>
          <p>Price: $${product.price.toFixed(2)}</p>
        </div>
      `;
    }

    productContainer.innerHTML = productsHTML;
  </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:34:16