Javascript DOM HTML Div Object create

Introduction

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

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

Click the button to create a DIV element with a red background color and some text.

View in separate window

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

<script>
function myFunction() {/*from   w w  w  . ja  va2 s.c  om*/
  var x = document.createElement("DIV");
  var t = document.createTextNode("This is a div element.");
  x.setAttribute("style", "background-color: red;");
  x.appendChild(t);
  document.body.appendChild(x);
}
</script>

</body>
</html>



PreviousNext

Related