How do you completely replace a function in JavaScript?
I got this code, but it doesn’t work. The DOM gets updated, though. What’s up with that?
<html>
<head>
<script id="myScript" type="text/javascript">
function someFunction() {
alert("Same old.");
}
</script>
</head>
<body>
<input type="button" onclick="someFunction();" value="A button." />
<script>
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();
</script>
</body>
</html>
JSfiddle here
Setting
.innerHTMLdoesn’t re-execute a script. If you really wanted to do that, you’d have to create a newscriptelement and append it to the DOM, which then overwrites what the previous script has done (not possible in all cases, of course).If you want to replace that function, just use
Of course, to replace only parts of the code (not knowing all of it) you could try regex and co. Still just reassign the new function to the variable: