EN
JavaScript - access body element
8
points
In this short article, we would like to show how to get <body> element reference in JavaScript.
Quick solution:
var bodyElement = document.body;
Warning:
document.bodycan benullif you access it when body is not ready (e.g. in<head>element).
Practical example
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Page title</title>
</head>
<body>
<script>
var bodyElement = document.body; // body element reference
console.log(bodyElement.outerHTML);
</script>
</body>
</html>