PDA

View Full Version : Beginning DOM



mmarkym
01-31-2011, 09:37 AM
Hi,

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."


<html>
<head>

<title>Trickier nesting, still</title>

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

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

alert(htmlElement.nodeName);

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

alert(headElement.nodeName);

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

var bodyElement = headElement.nextSibling;

var textElement = titleElement.firstChild;

alert(titleElement.nodeName);
alert(bodyElement.nodeName);
alert(textElement.nodeValue);



</script>



</head>
<body>
<div id="main-body">
<div id="contents">
<table>
<tr><th>Steps</th><th>Process</th></tr>
<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>
</table>
</div>
<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>
</div>
</div>
</body>
</html>

venegal
01-31-2011, 10: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?

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

the code worked for me (FF 3.6)

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