0

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>'));
anar khalilov
  • 16,993
  • 9
  • 47
  • 62
Domezchoc
  • 177
  • 2
  • 14
  • 3
    Your "before" HTML is invalid and the "after" is invalid too. So... –  Jun 26 '15 at 03:18
  • Of course you can see this example : http://stackoverflow.com/questions/918792/use-jquery-to-change-an-html-tag – Samphors Jun 26 '15 at 03:26
  • 1
    @squint is correct. You have list items without a list element. After you correct the html look into jquery replaceWith () – atomSmasher Jun 26 '15 at 03:28
  • @squint because sometime html get from clipboard data or user input that i have to validate after that – Domezchoc Jun 26 '15 at 03:59
  • @samphors in jquery when deep node i can not replace or it need to loop until no have non-whitelist. – Domezchoc Jun 26 '15 at 04:06

1 Answers1

1

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>
Community
  • 1
  • 1
rphv
  • 5,409
  • 3
  • 29
  • 47