lekso
lekso

Reputation: 1813

Append a JS to body element

why does message box not appear? Many thanks.

<!DOCTYPE html>
<html>
<head>
    <script src="jquery-1.8.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $('<script>alert("hi");</' + 'script>').appendTo(document.body);
    </script>
</head>
<body>
    <span>my test</span>
</body>
</html>

Upvotes: 0

Views: 289

Answers (1)

tckmn
tckmn

Reputation: 59273

You must wrap in in a $(document).ready.

Otherwise it won't be able to find body because it hasn't loaded yet.

$(document).ready(function() {
    $('<script>alert("hi");</' + 'script>').appendTo(document.body);
})

Upvotes: 3

Related Questions