1

i dont know a lot of javascript but one thing ive realized is doing this

function example()
{
document.getElementById("example").innerHTML="<script>document.write(example)</script>"
}

doesnt work! i understand this but is there another way of doing this same thing that does work?

karthikr
  • 97,368
  • 26
  • 197
  • 188
Hamzah Malik
  • 273
  • 2
  • 5
  • 13
  • 2
    You can not use `document.write` after page load either. Well you can, it is just going to blow up the page and make it a new one. – epascarello May 20 '13 at 19:49
  • 1
    **Why** do you want to **write** *JavaScript code* in an element? Specifically, the function that this code is in? – Ian May 20 '13 at 19:50
  • because i need the content to be added after user input, which activates the function. and it need to be javascript because its a varioable that i want adding – Hamzah Malik May 20 '13 at 19:54
  • 1
    Could you add a more complete example of what you're trying to achieve? – bfavaretto May 20 '13 at 20:14

2 Answers2

2

This approach worked for me:

<body>
    <div id="main">
    </div>

    <script>
    // create a script element
    var script = document.createElement('script');
    // fill its inner html with js code
    script.innerHTML = 'alert("Javascript");'
    // add it inside your target div and then profit!
    document.getElementById('main').appendChild(script);
    </script>
</body>

Edit: I've found more info about your problem here, I suggest you read the question, it has plenty of helpful answers and it also explains why your first approach did not work: Can scripts be inserted with innerHTML?

A simple vanilla approach of using this code to write data inside a div after the page has loaded could be done like this:

<html>
<head>
    <script>
        window.onload = function () {
            var script = document.createElement('script');
            script.innerHTML = 'alert("Javascript");'
            document.getElementById('main').appendChild(script);
        }
    </script>
</head>
<body>
    <div id="main">
    </div>
</body>
</html>
Community
  • 1
  • 1
BBog
  • 3,630
  • 5
  • 33
  • 64
-1

There is two error on your script. This is doesn't work, because variable name and function name equal to div id and this wrong method for javascript. You write a code to your div, but you don't run it. You can try that;

<div id="mydiv"></div>
<script>
function example()
{
document.getElementById("mydiv").innerHTML = eval("document.write('lololo')");
}
example();
</script>
Cem Demir
  • 152
  • 2
  • 6