Dynamically Inserting a Div containing a script

This example works through the code for adding a a div containing a display slot script call.

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
 <h4>You should see created divs below this if you inspect this element.</h4>
 <h4 id="endMarker">You should see created divs above this if you inspect this element.</h4>
<input id="index" value="0">
<button onclick="addElement( jQuery( '#index' ).val() );$( '#index' ).val( function( i, oldval ) { return parseInt( oldval, 10 ) + 1;} )">Add a Script Div</button>

JavaScript

function addElement (index) { 
	divID = "div-gpt-ad-1231231231-" + index;
  var newDiv = document.createElement( "div" ); 
  newDiv.setAttribute( "id", encodeURIComponent( divID ) );
  var newScript = document.createElement( "script" );
  newScript.type = 'text/javascript';
  var scriptContent = document.createTextNode( "googletag.cmd.push( function() { googletag.display( '" + encodeURIComponent( divID ) + "' ); } );" ); 
  newScript.appendChild( scriptContent ); //add the text node to the newly created div. 
  newDiv.appendChild( newScript ); //add the text node to the newly created div. 

  // add the newly created element and its content into the DOM 
  var currentDiv = document.getElementById( "endMarker" ); 
  document.body.insertBefore( newDiv, currentDiv ); 
}