Javascript DOM HTML Body Object get and create

Introduction

The Body object represents an HTML <body> element.

We can access a <body> element by using document.getElementsByTagName():

var x = document.getElementsByTagName("BODY")[0];

Click the button to set the background color of the document to red.

View in separate window

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

<p id="demo"></p>

<script>
function myFunction() {//from www.  j a  v a 2 s .c  o  m
  var x = document.getElementsByTagName("BODY")[0];
  x.style.backgroundColor = "red";
}
</script>

</body>
</html>

We can also access a <body> element by using the document.body property.

Create a Body Object

We can create a <body> element by using the document.createElement() method:

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



PreviousNext

Related