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

如何在JavaScript中为多个数据对象添加<div>标签并将每个对象数据单独包裹<div>元素

Solution: Group Table Data with Valid HTML Structure

Got it, let's fix this properly. The main issue here is that your current approach tries to wrap table rows in <div> elements, which doesn't work because HTML tables have strict structural rules—<div> can't be a direct child of <tbody> or <tr>, and browsers will just move those divs outside the table entirely. Here's a valid, clean solution:

Step 1: Fix the HTML Structure & JavaScript Code

Instead of using invalid divs, use multiple <tbody> elements (which is fully allowed in HTML) to group each dataset. Each <tbody> acts as a logical container for your feelings and feelings2 data. We'll also fix the invalid <div> inside <tr> (replace it with a <td> since <tr> can only contain table cells):

// Get the parent table element
const table = document.querySelector('.tables table');
// Clear existing content to start fresh
table.innerHTML = '';

// Function to generate a full tbody for a feelings dataset
function generateFeelingsGroup(feelingsArray, groupClassName = 'feelings-group') {
  let tbodyContent = `<tbody class="${groupClassName}">`;
  
  for (const { menuItem, description, value } of feelingsArray) {
    tbodyContent += `
      <tr class="rows">
        <td class="menuItem">${menuItem}</td>
        <!-- Replace div with td to follow table structure rules -->
        <td class="hide description">${description}</td>
        <td>${value}</td>
      </tr>
    `;
  }
  
  tbodyContent += '</tbody>';
  return tbodyContent;
}

// Add both datasets as separate tbody groups
table.innerHTML += generateFeelingsGroup(feelings);
table.innerHTML += generateFeelingsGroup(feelings2);

Step 2: Style the Groups (Optional)

If you want each <tbody> group to look like it's wrapped in a div (e.g., add borders, spacing), add CSS for the feelings-group class:

.tables table {
  border-collapse: separate;
  border-spacing: 0;
  width: 100%;
}

.feelings-group {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 16px;
  /* Make the tbody behave like a block element for proper spacing */
  display: table;
  width: 100%;
}

.feelings-group tr:last-child td {
  border-bottom: none;
}

.rows td {
  border-bottom: 1px solid #f0f0f0;
  padding: 8px;
}

Why This Works

  • Valid HTML: Multiple <tbody> elements are permitted in a single table, so this approach follows web standards and won't be broken by browser DOM correction.
  • Clear Grouping: Each dataset lives in its own logical container, exactly like you wanted with divs.
  • Styleable: You can customize the appearance of each <tbody> group to match your design needs, just like you would with a div wrapper.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 17:52:41