JavaScript在div中创建span元素

时间:2020-10-17 13:36:11

标签: javascript html

以下是满足我需要的HTML。它会在我通过JavaScript发送的值下方显示category:

<div id="category-order-id" class="additional-order-info">
   <!-- <span class="additional-order-info-grey">category:</span>
      Clothes -->
</div>

这是我的JavaScript

let orderCategory = document.getElementById("category-order-id");
orderCategory.textContent = `${order.category}`;
let categorySpan = document.createElement("span");
categorySpan.setAttribute("class", "additional-order-info-grey");
categorySpan.textContent = "category:";
orderCategory.appendChild(categorySpan);

此代码的作用是,它首先显示我使用JavaScript发送的Clothes值,并在其下面显示category

为什么在这里创建span元素是因为如果我将textContent中的orderCategory设置为span,就根本不会显示。{p>

我在做什么错了?

1 个答案:

答案 0 :(得分:3)

textContent属性替换元素中的所有内容。如果要保留order.category和“ category:”作为内容,则需要使用appendChild函数:

query
相关问题