rails sanitize pops out of <p> tag

1.1k views Asked by At

I have the following code

<p>
  <%= sanitize "<p>This is a test</p>" %>
</p>

I expected the sanitized html would show up between <p></p>. However it produces.

<p>
      </p>
<p>This is a test</p> 

When I change the enclosing <p></p> to <div></div>, the sanitized html shows up between <div></div> as I would expect.

Why does sanitizing html between <p></p> remove the sanitized html from the enclosing tag and place it after the enclosing tag?

How do I get the the sanitized html to show up in <p></p>?

3

There are 3 answers

0
janfoeh On BEST ANSWER

Nesting paragraph tags is not legal; the <p> tag only accepts phrasing content tags.

This is why the Chrome dev tools show a changed order - the browser is correcting the mistake as good as it can and moves the inner <p> out and next to it.

0
user2517182 On

It is an HTML specification thing. List are not suppose to be in paragraph tags.

More on this here

1
Andrey Sereda On

The reason why <p> are not removed by sanitize methods is that <p> tag is in the list of default allowed tags. Full list is:

del, dd, h3, address, big, sub, tt, a, ul, h4, cite, dfn, h5, small, kbd, code,
b, ins, img, h6, sup, pre, strong, blockquote, acronym, dt, br, p, div, samp,
li, ol, var, em, h1, i, abbr, h2, span, hr

More info: http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/sanitize