最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to insert a span tag inside a button tag? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 4

Tell me if this works the way you want:

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

element.innerHTML += "<span>Standard</span>";
  1. Create a <span> node using createElement.
  2. Change the innerText (or textContent) of the <span> node.
  3. Append the <span> node to the selected element.

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>

发布评论

评论列表(0)

  1. 暂无评论