Javascript DOM How to - Add new div element with text content








Question

We would like to know how to add new div element with text content.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
p {<!--from  w w w .  ja v  a  2s.  c  om-->
  border: 2px dashed green;
  padding: 10px;
  margin: 4px;
}

div {
  border: 2px dashed blue;
  padding: 10px;
  margin: 4px;
}
</style>
</head>
<body>
  <p>
  <div>original</div>
  </p>
  <script type='text/javascript'>
    var p = document.createElement('p');
    p.appendChild(document.createElement('div')).appendChild(document.createTextNode('new'));
    document.body.appendChild(p);
    
    </script>
</body>
</html>

The code above is rendered as follows: