簡體   English   中英

將 class 名稱<span>標簽替換為<sup>標簽</sup></span>

[英]Replace class name <span> tag to <sup> tag

我想將 span class 替換為<sup>標簽

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

見 html,

如果存在<sup>標簽,那么我想像這樣將<span> class 替換為<sup>標簽,

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

在if條件下

請檢查以下示例的 output

 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>

這可能是最好的解決方案:

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元素的 class 設置為span的 class,並將 innerHTML 設置為span的 innerText。

我希望這是有道理的。

如果您需要 JQuery 庫,那么我建議使用jquery-3.2.1.min.js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM