Javascript DOM How to - Add h1 and span elements to the DOM and set text








Question

We would like to know how to add h1 and span elements to the DOM and set text.

Answer


<!DOCTYPE html>
<html>
<body>
<script type='text/javascript'>
    var el =  document.createElement("h1")
    el.id="title";
    el.innerHTML = "Some title";
    document.body.appendChild(el);<!-- www. j  a  va2 s.c o  m-->
    var el2 =  document.createElement("span")
    el2.style.display="block";
    el2.style.width="100%";
    el2.innerHTML = "Some arb text";
    document.body.appendChild(el2);

</script>

</body>
</html>

The code above is rendered as follows: