Create element with dynamic code - Javascript DOM

Javascript examples for DOM:Element appendChild

Description

Create element with dynamic code

Demo Code

ResultView the demo in separate window

<html>
   <head></head>
   <body onload="onPageLoad()"> 
      <script>
   function onPageLoad()// w w w  .  j  a va 2 s  .c o  m
   {
      var testString = "This is the test";
      var divElement = document.createElement('div');
      divElement.innerHTML = '<h1 onclick="onClickFunc(\''+ testString + '\')">Click Me!</h1>';
      document.body.appendChild(divElement);
   }
   function onClickFunc(str)
   {
      console.log(str);
   }

      </script>  
   </body>
</html>

Related Tutorials