0

I have a Rails backend which sends strings like

<p>Hello world</p>

etc.

But no matter what I do

$('div#target').after(...) or $('div#target').html(...)

The string remains sanitized. How can I make it into valid HTML?

Note: on my client I only have a <script> tag

Code bit that sends the string:

function main() {
  jQuery(document).ready(function($){
    var body = "<%= @body %>";
    $('script#parentdiv').after("<div class='parent'></div>");
    $('.parent').html(body);
  });
The Whiz of Oz
  • 6,763
  • 9
  • 48
  • 85

2 Answers2

5
var body = "<%= @body %>";

needs to be

var body = "<%= @body.html_safe %>";
Joeman29
  • 712
  • 5
  • 14
2

If you specifically wish to use jQuery then

  var str = "hello, <b>my name is</b> jQuery.",
  html = $.parseHTML( str ), 
  // Append the parsed HTML
  $("#anyDomElement").append( html );`

This is straight from jQuery docs: http://api.jquery.com/jquery.parsehtml/

Otherwise this can also be done through native easily Creating a new DOM element from an HTML string using built-in DOM methods or prototype

Any string needs to be parsed and created as nodes of DOM to be understood by browser.

Community
  • 1
  • 1
anshulix
  • 197
  • 11