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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745625782a4636795.html
评论列表(0条)