Hi all!

I have a problem - surprise. I want to swap the content of my <div> (with the ID "content"), when the user press a bottom. I have tried using these, but with no result:

document.getElementById("content").innerHTML = "<script src=\"js/demo.js\" language=\"javascript\" type=\"text/javascript\"></script>";

$("<script src=\"js/demo.js\" language=\"javascript\" type=\"text/javascript\"></script>").appendTo('#content');

I can insert <p> tags with this method, but i can't use script tags this way.
So how do i insert a JavaScript to a specific <div> using Javascript or jQuery?

PS. I remove the content of #content like this:

jQuery('#content div').html('');

Recommended Answers

All 2 Replies

what about this

var cont = document.getElementById("content");
cont.innerHTML = "";
var s = document.createElement("script");
s.type = "text/javascript";
s.src = \"js\/demo.js\";

  1. You shouldn't append script element to a div or any other structural element of the document except the two main elements of the document: document body and document head.

  2. The src attribute of script element is (recently) flagged, and pasting script element as innerHTML will probably not trigger the load, while appending a new script element by DOM, may trigger, -but only once.

  3. Your mentioned methods are successful in creating a new script element, except that they will refuse to load the external file. So the only way to go with this, is appending a new script element to the document body or the document head using DOM methods while targeting legitimate elements; i.e.: document.body & document.head.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.