Domezchoc
Domezchoc

Reputation: 177

How do you replace an string HTML tag with another tag?

How to replace replace an string HTML non-whitelist tag with P tag ?

Example whitelist is p br tag

String Before

<p>hello</p>
<div class="test">hello world <br>
     <div>First LI</div>
     <div>Second LI <a href="">link</a></div>
</div>
<div class="fw">
     <p>shareeditflag <span>test</span></p>
</div>
<table>
     <tbody>
     </tbody>
</table>

String Expect

<p>hello</p>
<p class="test">hello world <br>
     <p>First LI</p>
     <p>Second LI <a href="">link</a></p>
</p>
<p class="fw">
     <p>shareeditflag <p>test</p></p>
</p>
<p>
     <p>
     </p>
</p>

In jquery way it can not be done because when the deep node has problem it require looping until no have non-whitelist ?

$('*:not(p,br)').replaceWith($('<p>' + this.innerHTML + '</p>'));

Upvotes: 0

Views: 446

Answers (1)

rphv
rphv

Reputation: 5537

Following the strategy outlined here, you can create a new <p> element, fill it with the contents of your old <div>s, insert the new element, and then remove the originals:

  var test = document.getElementsByClassName("test")[0];
  var fw = document.getElementsByClassName("fw")[0];

  var ptest = document.createElement("p");
  ptest.innerHTML = test.cloneNode(true).innerHTML;
  parent = test.parentNode;
  parent.insertBefore(ptest, test);
  parent.removeChild(test);

  var pfw = document.createElement("p");
  pfw.innerHTML = fw.cloneNode(true).innerHTML;
  parent = fw.parentNode;
  parent.insertBefore(pfw, fw);
  parent.removeChild(fw);

However, you'll have to fix the problems with your HTML first, because none of these methods can be counted on to function with malformed HTML. In this case, put the <li>s in a list, and put the <table> contents in a <tbody> (or table row and column). For example:

<p>hello</p>

<div class="test">
  hello world 
  <br>
  <ul>
     <li>First LI</li>
     <li>Second LI <a href="">link</a></li>
   </ul>
</div>

<table id="fw" class="fw">
  <tr>
    <td>
     <p>shareeditflag</p>
   </td>
  </tr>
</table>

Upvotes: 1

Related Questions