3

Is it possible to get JavaScript script tags inside jQuery .html() function?

function pleaseWork(){
    $('#content').html('<h3 style="color:#335c91">This is the header</h3><div class="holder"><script type="text/javascript" src="javascriptFile.js"></script></div>');
}

What I am trying to accomplish is when the user clicks on a button, this header and JavaScript code show up in the div content, right now when I click on the button, there is no header showing and it goes to a blank page and shows the JavaScript code (it works, but not how I would like it to work.)

4
  • 1
    Would using .getScript() be a better idea? What's in javascriptFile.js? Can you move it's functionality to your main JS file? Commented Oct 4, 2011 at 21:28
  • 1
    also why don't you create a script element, set the src, and append it to the parent element? I think this is the "cleaner" way of doing this. Commented Oct 4, 2011 at 21:30
  • I am brand new to JQuery and JavaScript...what do you mean by jsFiddle, .getScript() and Mala, no idea what you are talking about...google awaits, thanks for your help gentlemen, let me know if ya'll come up with something else Commented Oct 4, 2011 at 21:37
  • 1
    You want to display the contents of the javascript file within the div? Commented Oct 4, 2011 at 22:06

1 Answer 1

5

Escape the </script> tag, by replacing it with this: <\/script>
If that doesn't work, also surround the script with cdata tags.

Working demo: http://jsfiddle.net/BgxZN/1/

EDIT:
If you want to actually show the contents of the javascript file inside the div, you'll need to use an XMLHTTP request or an iframe.

New working demo: http://jsfiddle.net/BgxZN/13/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.