【问题标题】:Replace class name <span> tag to <sup> tag将类名 <span> 标签替换为 <sup> 标签
【发布时间】:2020-10-19 16:19:08
【问题描述】:

我想将 span 类替换为 &lt;sup&gt; 标签

<sup>
  <span class="wysiwyg-color-yellow">test</span>
</sup>
    

见html,

如果存在&lt;sup&gt; 标签,那么我想将&lt;span&gt; 类替换为&lt;sup&gt; 标签 像这样,

<sup class="wysiwyg-color-yellow">test</sup>

在if条件下

【问题讨论】:

标签: javascript jquery


【解决方案1】:

请检查以下示例的输出

const color = document.querySelector(".wysiwyg-color-yellow");
const sup = document.querySelector("sup");

if (color.nodeName === "SPAN") {
  sup.innerHTML = color.textContent; // here is removed the inner span
  sup.classList.add(color.getAttribute("class"));
}
<sup>
  <span class="wysiwyg-color-yellow">test</span>
</sup>

sup元素不止一个的情况

const colors = document.querySelectorAll("sup > span");

colors.forEach((color) => {
  const parent = color.parentNode;

  parent.innerHTML = color.textContent;
  parent.classList.add(color.getAttribute("class"));
});
<sup>
  <span class="wysiwyg-color-yellow">test</span>
</sup>
<sup>
  <span class="wysiwyg-color-green">test</span>
</sup>
<sup>
  <span class="wysiwyg-color-blue">test</span>
</sup>
<sup>
  <span class="wysiwyg-color-orange">test</span>
</sup>

【讨论】:

  • 虽然这在技术上确实有效,但它不会修改每个 sup 元素,并且只会将类更改为“所见即所得-颜色-黄色”,当跨度的类可能是其他东西时。
  • 关于only changes the class to" wysiwyg-color-yellow ", when the span's class could be something else 我已经更新了答案以分配给选定元素的类名。关于`它不会修改每个 sup 元素`你告诉我只有一个 sup 元素
  • @Mario ty 对我很有帮助。
  • @Mario 你能帮我解决这个问题吗.. stackoverflow.com/questions/62527376/…
【解决方案2】:

这可能是最好的解决方案:

var buttons = $("sup");

for(var i=0; i< buttons.length; i++){
    if (buttons[i].children[0]) {
        if (buttons[i].children[0].nodeName == "SPAN") {
            var spanElement = buttons[i].children[0];
            buttons[i].setAttribute("class", spanElement.getAttribute("class"));
            buttons[i].innerHTML = spanElement.innerText;
        }
    }
}

这会选择每个sup 元素,并检查其中是否有span。如果存在span 元素,则将sup 元素的类设置为span 的类,并将innerHTML 设置为span 的innerText。

我希望这是有道理的。

如果你需要 JQuery 库,那么我推荐使用jquery-3.2.1.min.js

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2015-03-26
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 2013-09-05
相关资源
最近更新 更多