Section 4.14. Frequently Asked Questions?


4.14. Frequently Asked Questions?

Q:

I understand text, and elements, and branches, but I'm still confused about exactly what a "node " is.

A:

Everything in a DOM tree is a node: elements, text, attributes, even comments. Since each piece of markup has some common properties, like a parent, and in most cases a name and children, the DOM groups these common properties into a Node object. Then, each different type of node adds its own unique properties to the common properties in the Node type.

For example, element nodes have a getAttribute() and setAttribute() method, because only elements can have attributes. But element nodes get the parent and childNodes properties from the Node object, since that functionality is shared by several different types of nodes.

Q:

But some nodes don't have a name. What happens if you use the nodeName property on something like a text node?

A:

If you try to use a property on a node where that property doesn't apply, you'll get a value like "null " or "undefined ". That's the DOM's way of telling you that it didn't know what you meant, or at least that what you meant didn't match up with the DOM tree the browser created from your markup.

So if you tried to access the nodeName property on a text node, you'd get an undefined value because, unlike elements, text nodes don't have names. Or, if you tried to use nodeValue on an element, you'd get an undefined value, because elements don't have values. An element can have attributes, but any text within the element will be in the element's child text nodes, and not available through the element's nodeValue property.

I like most of this DOM stuff so far, but all this null value and undefined stuff kind of freaks me out. Can't I just ask the node if it's an element, or text, or whatever?

You can! (well, sort of)

Every node has a property called nodeType, along with the nodeName and nodeValue proeprties that you've already seen. The nodeType property returns a number, and that number maps to a value stored in the Node class. There's a value for each type of node, so you can use these values to figure out exactly what kind of node you're working with, like this:

 if (someNode.nodeTypeHere's the nodeType property. It returns a number... == Node.ELEMENT_NODE)...that you can compare to the numbers defined in the Node class. {   // Do something with the element node } else if (someNode.nodeType == Node.TEXT_NODE)There are numbers defined for all the node types, including elements, text, and attributes. {   // Do somethingOnce you know what type of node you have, you can avoid using properties that would return null values. with the text node } 




Head Rush Ajax
Head Rush Ajax (Head First)
ISBN: 0596102259
EAN: 2147483647
Year: 2004
Pages: 241

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net