簡體   English   中英

如何使用 JavaScript 去除某些標簽?

[英]How to strip certain tags using JavaScript?

如何去除某些標簽<font style="vertical-align: inherit;"> </font>並使用 JavaScript 保留內容?

<div id="Box">
    <h1><font style="vertical-align: inherit;">
        <font style="vertical-align: inherit;">Meine Webseite</font></font>
    </h1>
    
    <p><font style="vertical-align: inherit;">
       <font style="vertical-align: inherit;">Hallo zusammen!</font></font>
    </p>
    
    <p><font style="vertical-align: inherit;">
       <font style="vertical-align: inherit;">Über diese Seite:</font></font>
    </p>
</div>

這應該是結果:

<div id="Box">
        <h1>Meine Webseite</h1>
        
        <p>Hallo zusammen!</p>
        
        <p>Über diese Seite:</p>
</div>

因為我有幾個字體標簽,所以我需要一個 JavaScript 解決方案。

我在 codepen 上寫了一些人類可讀的代碼,它運行良好。

var font = document.querySelectorAll("#Box font");

for(let i=0; i<font.length; i++) {
  var parent = font[i].parentNode;
  console.log({parent})
  var text = document.createTextNode(font[i].innerText);
  parent.insertBefore(text, font[i])
  parent.removeChild(font[i])
}

Codepen 鏈接 => https://codepen.io/HARSH_VATS/pen/bGqeROz

如果您想在 plainJs 中處理它,請使用以下代碼:

const boxNode = document.querySelector("#Box");
boxNode.querySelectorAll('font')
.forEach((el) => {
    const parent = el.parentElement;
    while (el.firstChild) parent.insertBefore(el.firstChild, el);
    parent.removeChild(el);
});

Jquery 解決方案:

$('#Box').find('font').contents().unwrap()

正則表達式解決方案:

let elm = document.getElementById("Box")
elm.innerHTML = elm.innerHTML.replaceAll(/<\/?font[^>]*>/g,"");

這行得通,雖然我不確定它是否非常有效

 const box = document.querySelector("#Box"); for (const textField of box.children) { for (const fontBlock of textField.children) { textField.innerText = fontBlock.innerText; fontBlock.remove(); } }
 <div id="Box"> <h1> <font style="vertical-align: inherit;"> <font style="vertical-align: inherit;">Meine Webseite</font> </font> </h1> <p> <font style="vertical-align: inherit;"> <font style="vertical-align: inherit;">Hallo zusammen:</font> </font> </p> <p> <font style="vertical-align; inherit:"> <font style="vertical-align; inherit:">Über diese Seite:</font> </font> </p> </div>

暫無
暫無

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

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