簡體   English   中英

如何在按鈕標簽內插入跨度標簽?

[英]how to insert a span tag inside a button tag?

我正在使用 querySelector 獲取一個 div 元素並且能夠更改按鈕名稱,但我也想插入一個 span 標簽。

var element = document.querySelector("#secondselectionbox"); //This is the div element

(element.childNodes[1].textContent = "Standard");  //Name of the button

我想將“標准”包裝在跨度標簽中。

我曾嘗試使用 createElement 創建一個跨度,但這只是將跨度附加到列表按鈕而不是按鈕內部。

告訴我這是否按您想要的方式工作:

var element = document.querySelector("#secondselectionbox");

element.innerHTML += "<span>Standard</span>";
  1. 使用createElement創建一個<span>節點。
  2. 更改<span>節點的innerTexttextContent )。
  3. Append 將<span>節點指向所選element

或者

您還可以設置所選elementinnerHTML ,但我會避免這樣做。

檢查下面的代碼片段:

 var element = document.querySelector("#secondselectionbox"); //This is the div element const span = document.createElement("span"); span.innerText = "Standard" element.appendChild(span); // You can also set the innerHTML, but I would avoid doing that // element.innerHTML = "<span>Standard</span>"
 span { color: red; }
 <div id="secondselectionbox"></div>

更新:基於 OP 的評論

如果您的 div 里面有多個按鈕,並且您希望在每個按鈕中添加一個 span 元素,您可以簡單地循環遍歷 div 的所有子節點,如果子節點是一個按鈕,您可以 append 給它一個跨度。

 var element = document.querySelector("#secondselectionbox"); //This is the div element Array.from(element.children).forEach(btn => { if (btn.tagName === "BUTTON") { const span = document.createElement("span"); span.innerText = "Standard" btn.appendChild(span); } });
 button { display: block; margin: 1rem 0; } span { color: red; }
 <div id="secondselectionbox"> <button></button> <button></button> <p>Not a button</p> <button></button> <p>Not a button</p> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM