← Back to all snippets
JAVASCRIPT

Traverse the DOM: Parents, Children, Siblings

Master JavaScript DOM traversal to navigate between parent, child, and sibling elements using properties like `parentElement`, `children`, `firstElementChild`, `nextElementSibling`, and `previousElementSibling`.

function domTraversalExample(elementId) {
  const startElement = document.getElementById(elementId);
  if (!startElement) {
    console.error(`Element with ID '${elementId}' not found.`);
    return;
  }

  console.log(`
--- Traversing from element with ID: ${elementId} (${startElement.tagName}) ---`);

  // 1. Parent Element
  const parent = startElement.parentElement;
  console.log('Parent:', parent ? parent.tagName : 'No parent');

  // 2. Children Elements (HTMLCollection)
  console.log('Children:');
  if (startElement.children.length > 0) {
    Array.from(startElement.children).forEach((child, index) => {
      console.log(`  Child ${index + 1}: ${child.tagName} (ID: ${child.id || 'N/A'})`);
    });
  } else {
    console.log('  No children elements.');
  }

  // 3. First and Last Child Elements
  const firstChild = startElement.firstElementChild;
  const lastChild = startElement.lastElementChild;
  console.log('First Child:', firstChild ? firstChild.tagName : 'N/A');
  console.log('Last Child:', lastChild ? lastChild.tagName : 'N/A');

  // 4. Next and Previous Sibling Elements
  const nextSibling = startElement.nextElementSibling;
  const previousSibling = startElement.previousElementSibling;
  console.log('Next Sibling:', nextSibling ? nextSibling.tagName : 'N/A');
  console.log('Previous Sibling:', previousSibling ? previousSibling.tagName : 'N/A');

  console.log('--------------------------------------------------');
}

// Example HTML Structure:
/*
<div id="grandparent">
  <div id="parent1">
    <span id="child1-1">Child 1-1</span>
    <span id="child1-2" class="target">Child 1-2 (Target)</span>
    <span id="child1-3">Child 1-3</span>
  </div>
  <div id="parent2"></div>
</div>
*/

// Simulate the HTML structure for the example if running in a non-browser environment
// In a browser, these elements would already exist.
if (typeof document !== 'undefined') {
  document.body.innerHTML = `
    <div id="grandparent">
      <div id="parent1">
        <span id="child1-1">Child 1-1</span>
        <span id="child1-2" class="target">Child 1-2 (Target)</span>
        <span id="child1-3">Child 1-3</span>
      </div>
      <div id="parent2"></div>
    </div>
  `;
  domTraversalExample('child1-2');
  domTraversalExample('parent1');
  domTraversalExample('grandparent');
} else {
  console.log('Running in a non-browser environment. Please run in a browser to see DOM traversal in action.');
}
How it works: This snippet provides a comprehensive guide to navigating the DOM tree using JavaScript. It demonstrates how to access an element's immediate `parentElement`, retrieve all its direct `children` (as an `HTMLCollection`), and find its `firstElementChild` and `lastElementChild`. It also shows how to find adjacent elements at the same level using `nextElementSibling` and `previousElementSibling`. These properties are crucial for moving around the DOM dynamically, allowing developers to target and manipulate related elements based on a starting point.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs