ebol4
ebol4

Reputation: 152

Appending a string of HTML+Javascript to an element causes strange behavior

http://jsfiddle.net/PeKdr/

Having a Javascript variable containing both HTML and Javascript causes some strangeness in the result window. Neither of the buttons, the one that calls appendTheString(), nor the one that calls springAnAlert(), function at all.

I expected this fiddle to append the new babby div to the foo div, as well as the script that would cause the alert box to come up with the button inside the babby div is pressed.

Upvotes: 0

Views: 91

Answers (2)

sidneyYi
sidneyYi

Reputation: 76

This fiddle maybe what you want. http://jsfiddle.net/PeKdr/8/

$("#button").click(function () {
   $('.foo').append("<div class='babby'>The Babby Div!</div>\<script\>alert(1);\<\/script\>");
});
window.showAlert = function(){
   $('.foo').append("<div class='babby'>The Babby Div!</div>\<script\>alert(2);\<\/script\>");
}

Upvotes: 0

Mr Lister
Mr Lister

Reputation: 46579

You cannot have </script> inside a script, because the </script> ends the script. Even if it's in quotes.

So the answer is to cut the string into pieces, none of which contains an entire end tag.

function append() {
    var stringToAppend = "<"+"div class='babby'>The Babby Div!<"+
        "/div><script>alert('This alert never happens!');<"+"/script>";
  $('.foo').append(stringToAppend);
}

Updated fiddle: http://jsfiddle.net/PeKdr/5/

Edit: oh, I see the very same solution was already given in a comment. But I swear I never saw the comment until I published this answer!

Upvotes: 1

Related Questions