How to create new HTML element dynamically in run time with JavaScript

1 Answer

0 votes
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div id="div_id">The exist div text</div>
<script type="text/JavaScript"> 

document.body.onload = addNewElement;

function addNewElement() 
{ 
  var newDiv = document.createElement("div"); 
  var newContent = document.createTextNode("The new div element text"); 
  newDiv.appendChild(newContent); // add the text node to new div

  var currentDiv = document.getElementById("div_id"); 
  document.body.insertBefore(newDiv, currentDiv); 
}

/*
run:

The new div element text
The exist div text
    
*/

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

 



answered Jun 12, 2016 by avibootz
...