4



<div id="example">

</div>


<script type="text/javascript">

  function insert() {
     var data = '<script type="text/javascript">  function test() {    a = 5;   }<\/script>';  
     $("#example").append(data);
  } 

  function get() {
     var content = $("#example").html();
     alert(content);
  }


</script>


<a href="#" onclick="insert();">INSERT</a>

<a href="#" onclick="get();">GET</a>


</body>
</html>

what i want to do:

when i click on insert, i want to insert this code into example div:

<script type="text/javascript">  function test() {    a = 5;   }<\/script>

when i click on get, i want to get that code, which i inserted there.

but when i click on insert, and then on get, there's no code.. where is problem ? thanks

3 Answers 3

4

According to your comment to Adam Bellaire, you want the script tag to display as normal text. What you are looking to do is encode the text with HTML entities, this will prevent the browser from processing it as normal HTML.

   var enc = $('<div/>').text('<script type="text/javascript">  function test() {    a = 5;   }<\/script>').html();
   $("#example").append(enc);
Sign up to request clarification or add additional context in comments.

Comments

1

This works:

function insert() {
 var data = '<script type="text/javascript">  function test() {    a = 5;   }<\/script>';  
 $('#example').text(data);
}

function get() {
 var content = $('#example').text(); 
 alert(content);
}

Comments

0

Are you checking for the code by browsing the live version of the DOM, using a tool like Firebug? If you are expecting to see your code rendered in your regular browser window, you won't, because the script tags are actually parsed when they are inserted, and script tags aren't visible elements in an HTML page.

1 Comment

yes, but is it possible to insert javascript code into page with jquery, but not parsed ? i want to insert it like raw string or text.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.