1

index.html:

<script id="change">
    function methods(){
        return 1;
    }
</script>

js.js:

...
button.addEventListener("click", ()=>{
    document.querySelector("#change").innerHTML = `
        function methods(){
            return 0;
        }
    `;
}
...

Console before clicking button:

>>>methods();
1

Console after clicking button:

>>>methods();
1

How can I update this function?

2
  • I've fixed the Markdown issues (code blocks need an empty line before them). Commented Nov 20, 2020 at 14:25
  • can't you just use let function1 = function2 or something similar? Commented Nov 20, 2020 at 14:45

2 Answers 2

2

Instead of rewriting the script tag content, just overwrite the methods function.

This can be demonstrated easily using the following snippet:

console.log(methods());

methods = function() {
  return 0;
}

console.log(methods());
<script id="change">
    function methods(){
        return 1;
    }
</script>

In the case of your code, in the event handler just do the same:

...
button.addEventListener("click", ()=>{
  methods = function() {
    return 0;
  }
});
...

Edit following OP comment

OP has commented stating that the function content is read out of a database and is stored in a string. This changes the solution required to:

console.log(methods());

var functionText = "return 0;";
methods = Function(functionText);

console.log(methods());
<script id="change">
    function methods(){
        return 1;
    }
</script>

In your original code, this would then look like:

...
button.addEventListener("click", ()=>{
  methods = Function("return 0;");
});
...
Sign up to request clarification or add additional context in comments.

3 Comments

I am sure this works, but, I am getting some js from database as string
@JasurbekLazizjonov Probably would have been useful to have put that in the question as that does change the problem. Let me have a think and update the answer
@JasurbekLazizjonov I've updated to reflect the requirement you mentioned in your comment
1

This is how it works.

let button = document.querySelector('button');

button.onclick = function() { document.querySelector("#change").innerHTML = `
        function methods(){
            return 0;
        }
    `;
}
<script id="change">
    function methods(){
        return 1;
    }
</script>

<button>button</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.