admin管理员组文章数量:1434921
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.
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.
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.
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.
Share Improve this question edited Apr 6, 2021 at 6:20 chocpooh asked Apr 5, 2021 at 15:10 chocpoohchocpooh 251 silver badge6 bronze badges2 Answers
Reset to default 4Tell me if this works the way you want:
var element = document.querySelector("#secondselectionbox");
element.innerHTML += "<span>Standard</span>";
- Create a
<span>
node usingcreateElement
. - Change the
innerText
(ortextContent
) of the<span>
node. - Append the
<span>
node to the selectedelement
.
OR
You can also set the innerHTML
of the selected element
but I would avoid doing that.
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 ment
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.
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>
本文标签: javascripthow to insert a span tag inside a button tagStack Overflow
版权声明:本文标题:javascript - how to insert a span tag inside a button tag? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745625781a2666960.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论