[英]JavaScript create span element inside div
The following is the HTML that does what I want.以下是执行我想要的 HTML。 It displays
category:
and beneath a value that I send in JavaScript.它显示
category:
和我在 JavaScript 中发送的值下方。
<div id="category-order-id" class="additional-order-info">
<!-- <span class="additional-order-info-grey">category:</span>
Clothes -->
</div>
And here is my JavaScript这是我的 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);
What this code does, it that it first displays Clothes
value that I send with JavaScript and beneath it display category
.这段代码的作用是,它首先显示我用 JavaScript 发送的
Clothes
值,并在其下方显示category
。
Why I am creating a span
element here is because if I set textContent
of orderCategory
it wil not display the span
at all.为什么我在这里创建
span
元素是因为如果我设置orderCategory
textContent
它根本不会显示span
。
What am I doing wrong here?我在这里做错了什么?
textContent property replaces all the content in the element. textContent 属性替换元素中的所有内容。 If you want to keep order.category and "category:" as content, you need to use the appendChild function:
如果要保留 order.category 和 "category:" 作为内容,则需要使用 appendChild 函数:
let orderCategory = document.getElementById("category-order-id");
const catTextContent = document.createElement("span");
catTextContent.textContent = order.category;
let categorySpan = document.createElement("span");
categorySpan.setAttribute("class", "additional-order-info-grey");
categorySpan.textContent = "category:";
orderCategory.appendChild(catTextContent);
orderCategory.appendChild(categorySpan);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.