JS: Navigate DOM Tree

By Xah Lee. Date: . Last updated: .

This page is a tutorial of JavaScript navigating the DOM tree.

DOM has several methods that lets you navigate the DOM tree. That is, if you have a node, you can obtain its parent node, or sibling node, or it's children nodes.

Get Previous/Next Sibling

element.previousElementSibling → Value is the previous sibling that's not a white space node. Value is null if element does not have sibling.

element.nextElementSibling → Value is the next sibling that's not a white space node. Value is null if it element does not have sibling.

node.previousSibling → Value is the previous sibling of node, or null if it doesn't exist. This may be whitespace nodes.

node.nextSibling → Value is the next sibling of node, or null if it doesn't exist. This may be whitespace nodes.

〔►see JS: DOM Whitespace Nodes

// their difference is possibility of whitespace node

document.getElementsByTagName("p")[0].nextElementSibling; // never whitespace node

document.getElementsByTagName("p")[0].nextSibling; // may be whitespace node

play with browser console: JavaScript nextElementSibling test

Get Child Nodes

element.children → Value is a live collection of all non-whitespace children of element. 〔►see JS: DOM Whitespace Nodes

node.childNodes → Value is a live collection of all children of node.

// example of getting children elements

var xx = document.getElementsByTagName("div")[0].childNodes;

xx.length;

Get First/Last Child

element.firstElementChild → Value is the first non-whitespace child node of element, or null if it doesn't exist.

node.firstChild → Value is the first child of node, or null if it doesn't exist.

node.lastChild → Value is the last child of node, or null if it doesn't exist.

Get Parent Node

node.parentNode → Value is the parent of node, or null.

Basic DOM Methods Topic

  1. JS: Basic DOM Methods
  2. JS: Get Elements by ID, Tag, Name, Class, CSS Selector
  3. JS: Get Element's Attribute Value
  4. JS: Set Element's Attribute Value
  5. JS: List/Add/Remove Class Attribute
  6. JS: Node Type, Node Name, Node Value
  7. JS: Navigate DOM Tree
  8. JS: Add / Remove Event Handler
Like what you read? Buy JavaScript in Depth