Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Apr 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    using innerHTML to run a script

    I have a script in the head of the document with the following line:
    document.getElementById("txtHint").innerHTML="<script>foo();<\/script>";

    and I want it to be used to run function foo() in the body:

    <script>
    function foo(){
    console.log("FOO");
    }

    </script>
    <div id="txtHint"></div>

    but it doesn't write anything in console. what is the problem?

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,925
    Thanks
    56
    Thanked 549 Times in 546 Posts
    possibly one of the weirder attempts at a function call I have seen.

    but it's a basic problem: your getElementById runs in the head, which comes before the body

    your "txtHint" div gets created in the body. ie, after your script has run

    so the code tries to get an element that doesn't exist yet

    and it pretty much goes all downhill from there. there may be other conceptual problems with what you are trying to do, but that's the dealbreaker for now.

    can I ask why you are trying to do it that way instead of something a little more, uh... normal?

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,299
    Thanks
    10
    Thanked 585 Times in 566 Posts
    <script> tags created with innerHTML don't work.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #4
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,042
    Thanks
    0
    Thanked 251 Times in 247 Posts
    If you just want to call foo(), then why don't you just call it directly? Why do you need innerHTML to call it?

  • #5
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,628
    Thanks
    0
    Thanked 648 Times in 638 Posts
    If you want to add a script to the page then just use the correct DOM call to create the script tag. It is one of the situations where you must use the DOM rather than innerHTML.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •