Javascript DOM HTML Section Object create

Introduction

We can create a <section> element via the document.createElement() method:

var x = document.createElement("SECTION");

Click the button to create a SECTION element containing a H1 and P element.

View in separate window

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>

<script>
function myFunction() {// ww w  . j a  v a  2 s .c om
  var x = document.createElement("SECTION");
  x.setAttribute("id", "mySection");
  document.body.appendChild(x);

  var heading = document.createElement("H1");
  var txt1 = document.createTextNode("Section Heading");
  heading.appendChild(txt1);
  document.getElementById("mySection").appendChild(heading);

  var para = document.createElement("P");
  var txt2 = document.createTextNode("Some text in section..");
  para.appendChild(txt2);
  document.getElementById("mySection").appendChild(para);
}
</script>

</body>
</html>



PreviousNext

Related