Moving around in a DOM tree
You already know how the document object can help you find an element with a particular id attribute, but there are a lot of other ways you can get around in a DOM tree. Since each node has a parent, and most element nodes have children, you can move up and down in the DOM tree using these connections.
body divNode is the variable name pointing to the <div> in this diagram.divNode.parentNode You can get the parent of the <div>, which is the <body> element, by using the <div> node's parentNode property. div Start reading HERE! Everything in this diagram starts with this <div>. Here's the <div> that we're starting from. It's a node object in the DOM tree. divNode.childNodes The childNodes property gives you an array of all the <div>'s child nodes. divNode.firstChild If you want to go straight to the first child, use the firstChild property of the <div>'s node object. divNode.lastChild You can get to the last child of the <div> with the lastChild property. "Our " em " trees are a favorite for nearby neighbors." "breadth-first" You could use the <em> node's firstChild, lastChild, or childNodes property to get to this text.
Sweet! Now I can find any element I want, move up and down the DOM tree... I'll bet I can get element names and text values, too, right?
The node knows... pretty much everything.
Remember, everything in a DOM tree is a node. Elements and text are special kinds of nodes, but they're still nodes. Anytime you have a node, you can get the name of the node with nodeName, and the value of the node with nodeValue .
You've got to be careful what type of node you're working on, though, or you could end up getting a null value when you're expecting the name of an element or a string of text. An element node has a name, like "div" or "img", but won't have a value. And a text node won't have a name, but it will have a value: the actual text stored in the node.
Let's take a look and see how this works: