How to strip certain tags using JavaScript?

Viewed 89

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.

4 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

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);
});

Jquery Solution :

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

Regex Solution :

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

This works, although I'm not sure if it is very efficient

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>

Related