[英]how to insert a span tag inside a button tag?
I am getting a div element using querySelector and able to change the button name, but I want to insert a span tag as well.我正在使用 querySelector 获取一个 div 元素并且能够更改按钮名称,但我也想插入一个 span 标签。
var element = document.querySelector("#secondselectionbox"); //This is the div element
(element.childNodes[1].textContent = "Standard"); //Name of the button
I want to wrap the "Standard" in span tag.我想将“标准”包装在跨度标签中。
I have tried to create a span using createElement, but that just appends the span to the list buttons instead of inside the button.我曾尝试使用 createElement 创建一个跨度,但这只是将跨度附加到列表按钮而不是按钮内部。
Tell me if this works the way you want:告诉我这是否按您想要的方式工作:
var element = document.querySelector("#secondselectionbox");
element.innerHTML += "<span>Standard</span>";
<span>
node using createElement
.createElement
创建一个<span>
节点。innerText
( or textContent
) of the <span>
node.<span>
节点的innerText
(或textContent
)。<span>
node to the selected element
. <span>
节点指向所选element
。 OR或者
You can also set the innerHTML
of the selected element
but I would avoid doing that.您还可以设置所选
element
的innerHTML
,但我会避免这样做。
Check the code snippet below:检查下面的代码片段:
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>
UPDATE: Based on OP's comment更新:基于 OP 的评论
If your div has multiple buttons inside them and you wish to add a span element inside each of those buttons, you can simply loop over all the child nodes of the div and if the child is a button you can append a span to it.如果您的 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.