Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip certain tags using JavaScript?

Tags:

javascript

How can I strip certain tags <font style="vertical-align: inherit;"> </font> and keep the contents using 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>

This should be the result:

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

Since I have several font tags I require a JavaScript solution for all.

like image 354
ThankFull Avatar asked May 20 '26 19:05

ThankFull


2 Answers

I wrote some human-readable code on codepen and it works fine.

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 Link => https://codepen.io/HARSH_VATS/pen/bGqeROz

like image 112
Badmaash Avatar answered May 22 '26 09:05

Badmaash


If you wanna handle it in plainJs use code below:

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);
});
like image 21
shahabvshahabi Avatar answered May 22 '26 10:05

shahabvshahabi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!