Get body element of site using only javascript

Solution 1:

Although the @Brendan's answer is accepted and correct.

It is simple, short and faster enough to get a body element using

document.body;

It does the same as we can do with document.getElementsByTagName('body')[0];, and it should be in the list of answers.

Solution 2:

Try this:

<script>
window.onload = function get_body() {

  body = document.getElementsByTagName('body')[0];
}

</script>

Allow me to explain. The window.onload is so that the HTML loads before the script is executed. Even though there is only one body tag this is the method i use^. Basically, it finds the "first" body tag there is, then I tell it to just get the body element itself and not all the other attributes and child nodes that go along with it using an index of [0]. If you want everything to do with the body tag then lose the index of 0. Hope this Helps!