简体   繁体   中英

JavaScript create span element inside div

The following is the HTML that does what I want. It displays category: and beneath a value that I send in 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

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 .

Why I am creating a span element here is because if I set textContent of orderCategory it wil not display the span at all.

What am I doing wrong here?

textContent property replaces all the content in the element. If you want to keep order.category and "category:" as content, you need to use the appendChild function:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM