0

I am trying to insert string inside body part of my html document using javascipt. The string which i want to insert contains some script tags also. For example :

  var str = "<div> some text </div>
             <script src='/Scripts/jquery-1.7.2.js' type='text/javascript'></script>";

Now when i insert the above string using jquery , like :

 $('body').html(str);

It will insert the string and load the jquery also. But when i insert this string using javascript, like :

document.getElementsByTagName('body')[0].innerHTML = str;

This will not load the jquery script in the browser. Can anyone tell me how can i achieve the same using javascript ?

Tom Rider
  • 2,747
  • 7
  • 42
  • 65
  • It should work as expected, what if you try the old way of inserting elements in HTML? @TheDOCTORfromTARDIS yes it is.. – Wouter J Jan 12 '13 at 11:04

2 Answers2

0

http://www.jquery4u.com/javascript/dynamically-load-jquery-library-javascript/ here you have a good guide. So in your case you can try this:

  var head= document.getElementsByTagName('body')[0];
  var script= document.createElement('script');
  script.type= 'text/javascript';
  script.src= '/Scripts/jquery-1.7.2.js';
  head.appendChild(script)
Pieter Willaert
  • 879
  • 13
  • 36
0

Problem is, that if you are inserting scripts with innerHTML, the scripts will not be executed. No browser will do this because of security issues. jquery implemented a way around this. You can find further information and a solution in pure javascript here: Executing <script> elements inserted with .innerHTML

Community
  • 1
  • 1
Alex
  • 2,106
  • 16
  • 15