Javascript Element How to - Create new pre tag and assign value








Question

We would like to know how to create new pre tag and assign value.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--  w  ww .  j av a 2  s .c o  m-->
    document.querySelector("div").style.background = "black";
    var pre = document.createElement("pre");
    pre.textContent = document.body.innerHTML.trim();
    document.body.appendChild(pre);
}
</script>
</head>
<body>
  <div>first div</div>
  <div>second div</div>
</body>
</html>

The code above is rendered as follows: