AwaisMehnga
AwaisMehnga

Reputation: 41

how to Append defined functions to script tag of html

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>

Upvotes: 0

Views: 280

Answers (2)

Nitheesh
Nitheesh

Reputation: 19986

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>

Upvotes: 0

Jaromanda X
Jaromanda X

Reputation: 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>

Upvotes: 1

Related Questions