Replacing function contents dynamically in JavaScript
<p>How do you completely replace a function in JavaScript? </p>

<p>I got this code, but it doesn't work. The DOM gets updated, though. What's up with that?</p>

<pre><code>&lt;html&gt;
&lt;head&gt;
    &lt;script id="myScript" type="text/javascript"&gt;
        function someFunction() {
            alert("Same old.");
        }
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;input type="button" onclick="someFunction();" value="A button." /&gt;
&lt;script&gt;
    function replace() {
        var oldFunctionString = someFunction.toString();
        var oldContents = oldFunctionString.substring(oldFunctionString.indexOf("{") + 1, oldFunctionString.lastIndexOf("}") );
        var newCode = "alert(New code!);";        
        var newFunctionString = "function someFunction(){"+newCode+"}";
        var scriptTag = document.getElementById('myScript');

        scriptTag.innerHTML = scriptTag.innerHTML.replace(oldFunctionString,newFunctionString);
    }

    replace();
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>JSfiddle <a href="http://jsfiddle.net/6yAaw/" rel="nofollow">here</a></p>
