Search code examples
javascriptappendappendto

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>

Solution

  • 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);
    })