title: Trying to build HTML elements by code, functions included
body: <p>This is my first post, hoping someone can help me:</p>
  
  <p>I wish to build a web project, where all the HTML elements are stored in database and taken from it to build the web page.</p>
  
  <p>i found a problem with the buttons, i cannot find a way to store the function for a button, i´m using Jquery to build the elements, for now the test element definitions are simulated in some arrays i left at the start of my Js file, the only way i can make the buttons to work is if the functions are hardcoded in the Js file, is there a way for me to bring the functions from database too? and having them in an array?</p>
  
  <p>this is my project sample:</p>
  
  <p>HTML</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;!--script src="functions.js"&gt;&lt;/script--&gt;
  &lt;script src="system.js"&gt;&lt;/script&gt;
  &lt;!--script src="elements.js"&gt;&lt;/script--&gt;
  
  &lt;/head&gt;
  &lt;body&gt;
  
  &lt;body onload="addElements()"&gt;
  
    &lt;div id="div1"&gt;&lt;/div&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>JS File</p>
  
  <pre><code>/**
  VARIABLE DEFINITIONS
  THESE ARE SUPPOSED TO COME FROM A DATABASE
  STILL UNKNOWN HOW TO BRING THE FUNCTIONS, AS STRING THEY ARE NOT ALLOWED. FOR NOW THERE ARE TEST FUNCTIONS.
  **/
  
  let buttonIds = ['btn1', 'btn2'];
  let buttonText = ['Show Text', 'Show HTML'];
  let buttonFunc = [alert1, alert2];
  //let buttonFunc = ['alert("Hi");', 'alert("Hello");'];
  let paragraphs = ['This is some &lt;b&gt;bold&lt;/b&gt; text in a paragraph.', 'another &lt;b&gt;bold&lt;/b&gt; test'];
  
  
  //HELPER FUNCTIONS
  // **** THESE ARE SUPPOSED TO COME FROM DATABASE, UNKNOWN HOW TO DO IT. ****
  
  function alert1() {
      alert("Hi");
  }
  
  function alert2(){
      alert("Hello");
  }
  
  
  
  
  function addElements(){ 
      for(var p=0; p&lt;paragraphs.length; p++){ addParagraphs('#div1', paragraphs[p]);                  }
      for(var i=0; i&lt;buttonIds.length; i++) { createButton( '#div1', buttonIds[i]  , buttonText[i]);  }
  }
  
  // ANY ELEMENTS FUNCTION IS DEFINED HERE ONCE THE PAGE IS LOADED.
  $(document).ready(function(){
      for(var x=0;x&lt;buttonIds.length; x++){ activateButton(buttonIds[x], buttonFunc[x]); }
  });
  
  
  //HELPER FUNCTIONS USED TO BUILD THE HTML ELEMENTS ON THE MAIN PAGE.
  function addParagraphs(location, text){
    $(location).append('&lt;p id="test"&gt;'+text+'&lt;/p&gt;');
  }
  
  
  function createButton(location, id, text){
  var definition;
  
  definition = "&lt;button id="+id+"&gt;"+text+"&lt;/button&gt;";
  $(location).append(definition);
  }
  
  
  function activateButton(buttonId, functionName){
    var composedId = "#"+buttonId;
      $(composedId).click(functionName);
  }
  </code></pre>