DOM: Navigate DOM Tree

By Xah Lee. Date: . Last updated: .

Here's how to navigate the DOM tree. That is, if you have a node, you can get its parent node, sibling node, or children nodes.

Get Previous/Next Sibling

// their difference is possibility of whitespace node

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

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

Get Child Nodes

// example of getting children elements

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

xx.length;

Get First/Last Child

Get Parent Node

Basic DOM How-To

  1. DOM: Basic DOM Methods
  2. Get Elements by ID, Tag, Name, Class, CSS Selector
  3. Change CSS
  4. Change Node Content
  5. Create/Insert Node
  6. Remove Node
  7. Get Element's Attribute Value
  8. Set Element's Attribute Value
  9. List/Add/Remove Class Attribute
  10. Add/Remove Event Handler
  11. DOM: Navigate DOM Tree
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon