View Full Version : Beginning DOM

01-31-2011, 10:37 AM

I'm new to programming with the DOM and new to this forum as well. I have the code below showing a web page that is simply trying to alert the user of recognized DOM nodes. I am not getting the bodyElement or textElement to be recognized by the browser. The error states that "an object is required."


<title>Trickier nesting, still</title>

<script language="JavaScript" type="text/javascript">

var myDocument = document;
var htmlElement = myDocument.documentElement;


var headElement = htmlElement.getElementsByTagName("head")[0];


var titleElement = headElement.getElementsByTagName("title")[0];

var bodyElement = headElement.nextSibling;

var textElement = titleElement.firstChild;



<div id="main-body">
<div id="contents">
<tr><td>1</td><td>Figure out the <em>root element</em>.</td></tr>
<tr><td>2</td><td>Deal with the <span id="code">head</span> first,
as it's usually easy.</td></tr>
<tr><td>3</td><td>Work through the <span id="code">body</span>.
Just <em>take your time</em>.</td></tr>
<div id="closing">
This link is <em>not</em> active, but if it were, the answers
to this <a href="answers.html"><img src="exercise.gif" /></a> would
be there. But <em>do the exercise anyway!</em>

01-31-2011, 11:08 AM
Using nextSibling like that is always problematic, because you might have invisible text nodes in there (headElement.nextSibling.nextSibling would probably work in this case, but you don't want to do that).

If you really need that nextSibling functionality, you can write your own function that loops through the siblings until it finds one that has nodeType 1 (and thus isn't a text node) and returns that.

But I really don't see why you need that at all. What's wrong with document.getElementsByTagName('body')[0] for getting the body?

01-31-2011, 11:15 AM
what browser do you use?

the code worked for me (FF 3.6)

01-31-2011, 11:45 AM
The document needs, also, a certain Doctype, otherwise any browser will interpret the codes in his quirks or "almost" standard mode.