what is the corrent way to get a reference to the body?

J

Jake Barnes

I've been doing this to get a reference to the body node of a document,
but I'm sure there must be something simpler than this:

var arrayOfBodyElements = document.getElementsByTagName("body");
var referenceToBodyNode = arrayOfBodyElements[0];


I tried:

var referenceToBodyNode = document.body;

and:

var referenceToBodyNode = window.body;

both of which got me "body undefined".

So what is the right way to get a reference to the body?
 
V

VK

Jake said:
I tried:
var referenceToBodyNode = document.body;
and:
var referenceToBodyNode = window.body;
both of which got me "body undefined".
So what is the right way to get a reference to the body?

The right way is the first one:
var bodyRef = document.body.

The problem is that this object doesn't exist until onload event is
fired for the window: this is why you were getting undefined.

So in order to get a reference to document.body you have to use
window.onload handler and finish collecting DOM references from there.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top