1

I am a beginner in JavaScript/HTML.

I'm learning my way around the DOM and JavaScript and am using the following page to explore accessing nodes via JavaScript:

http://franklyanything.com/test2.html

As you can see in the snippet of JavaScript I put in the Head, I'm trying to access the 2nd child of the <html> element, which should be the Body element.

However each time I run the page nothing happens and Firebug reports the variable as undefined. I have no problems if I change the index from [1] to [0]. This correctly identifies the <html> tag.

I'm stumped. What can I try next?

2 Answers 2

4

document.childNodes[0] is not the <html> element. It is the doctype declaration.

<!DOCTYPE HTML PUBLIC "...> 

You can access the <body> node directly using document.body, and get its node name using document.body.nodeName.

If you want to access it using childNodes, try,

document.childNodes[1].childNodes[2].nodeName // document.childNodes[1] => html // document.childNodes[1].childNodes[0] => head // document.childNodes[1].childNodes[1] => whitespace (text node) // document.childNodes[1].childNodes[2] => body 

If there is no whitespace between <head> and <body>, then, of course, the <body> element will be at position 2 or index 1 in <html> child nodes.

If you remove the doctype declaration, and the space between head and body, then your

document.childNodes[0].childNodes[1] 

will work as expected.

Sign up to request clarification or add additional context in comments.

Comments

1

The true problem, I think, is that you are calling the code before the document is ready.

window.onload=function(){ var theBodyNode = document.childNodes[0].childNodes[1]; alert(theBodyNode.nodeName); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.