4

On my website I load html, which is rendered at the server (nodejs), and insert it at the right position (most time a div with id content).

How would I insert the received html on the client, so that included script tags are executed?

I am using on the client side underscore and handlebars. But vanillajs is also possible of course.

PS: Here is an example to show the difference between jQuery.html() and setting the innerHTML-property:

http://jsfiddle.net/waxolunist/VDYgU/3/

Christian
  • 3,503
  • 1
  • 26
  • 47

3 Answers3

3

with jQuery

$('div#content').html(loaded_html);

without:

getElementById('content').innerHTML = loaded_html;

While possible to do it your way, a better idea might be to send json and render pages in the browser using the same templates you (possibly) use in the server. I'm using doT, which I think to be the best of all JavaScript based templates (like EJS, underscore).

esp
  • 7,314
  • 6
  • 49
  • 79
  • Yes, I swiched to jquery before your answer already. It works actually different and so script get executed. InnerHTML does not work for me (Chrome 26). I accept your answer though. I am rendering the html serverside only in some cases not in all. On the client I am using depending on the use case handlebars. – Christian May 10 '13 at 15:15
0

You could leverage jQuery to do that. Just with

$.load("#divname").load(url)

http://api.jquery.com/load/

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43
0

There is some problem with your character escaping, please use jshint. Otherwise it is pretty simple to use like

var script1 = "content for jQuery";
var script2 = "content for javascript";

$(document).ready(function (){
    $('#content1').html(script1);
    document.getElementById('content2').innerHTML = script2;
})
AlexB
  • 7,302
  • 12
  • 56
  • 74
shikhar chauhan
  • 431
  • 1
  • 4
  • 9