0

Hi: I want to append a js function something like function amb(){console.log("hello")} inside the script tag. But There is a problem in this. Because as the function is append to script tag it says function is not defined when i try to call. if you understand the problem or have any solution to it please help me. Thanks a lot...

 <script id="append_here">
        // the appended function goes in this script
    </script>
    <script>
        a = `function amb() { console.log('hello')}`
        document.getElementById('append_here').append(a)
    </script>
    <div id="a">
        <button onclick="amb()"> amb</button>

    </div>

1
  • Can you describe why you want to do that? Commented Sep 6, 2022 at 11:43

2 Answers 2

1

You can't append content to a script and have the browser "re-parse" the script

You can create a new script tag, add the content, and append that to the body

<script>
  const a = `function amb() { console.log('hello')}`;
  const scr = document.createElement('script');
  scr.textContent = a;
  document.body.append(scr);
</script>
<div id="a">
  <button onclick="amb()"> amb </button>

</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot brother, I have searched for more than seven hours, and you just solved my problem in a snap of finger. May Allah help you a lot
0

You can use eval aswell

<script id="append_here">
  // the appended function goes in this script
</script>
<script>
  a = `function amb() { console.log('hello')}`;
  document.getElementById("append_here").append(eval(a));
</script>
<div id="a">
  <button onclick="amb()">amb</button>
</div>

2 Comments

of course, that simply appends the word undefined to that script tag ... you get the same result if you just eval(a) without adding the result to the script for absolutely no reason :p
Thanks a lot for your precious answer, it works too and I'm happy with the results. May Allah gives you more power to help other

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.