Locked lesson.
About this lesson
What is a DOM node and how do you navigate them.
Exercise files
Download this lesson’s related exercise files.
Navigating DOM Nodes.docx59.2 KB Navigating DOM Nodes - Solution.docx
59.2 KB
Quick reference
Navigating DOM Nodes
Nodes are basically just another way to reference DOM elements.
When to use
Sometimes it's appropriate to use nodes, other times it's appropriate to use DOM elements like we have in the past.
Instructions
We can access the node hierarchy using these items:
parentNode
childNodes[nodenumber]
firstChild
lastChild
nextSibling
previousSibling
To access the text of this p tag <p id="first">Hello World</p> we'd use:
var myVar = document.getElementById("first").firstChild.nodeValue;
To access a specific node (when there's more than one) call their indext number (like an array):
var myVar = document.getElementById("first").childNodes[0].nodeValue;
To access Siblings:
var myVar = document.getElementById("first").nextSibling.innerHTML;
var myVar = document.getElementById("first").previousSibling.innerHTML;
Hints & tips
- Sometimes you'll use Nodes, sometimes DOM elements
- As you gain experience, it will become obvious when to use which
Lesson notes are only available for subscribers.