JAVASCRIPT
Traverse the DOM Tree with JavaScript
Learn how to navigate the Document Object Model (DOM) using JavaScript, accessing an element's parent, children, and siblings to locate specific elements.
const currentElement = document.getElementById('child-element');
// Get the direct parent element
const parent = currentElement.parentNode;
console.log('Parent:', parent ? parent.id : 'None');
// Get all direct child elements (HTMLCollection)
const children = parent ? parent.children : [];
console.log('Children count:', children.length);
// Get the first direct child element
const firstChild = parent ? parent.firstElementChild : null;
console.log('First Child:', firstChild ? firstChild.id : 'None');
// Get the last direct child element
const lastChild = parent ? parent.lastElementChild : null;
console.log('Last Child:', lastChild ? lastChild.id : 'None');
// Get the next sibling element
const nextSibling = currentElement.nextElementSibling;
console.log('Next Sibling:', nextSibling ? nextSibling.id : 'None');
// Get the previous sibling element
const prevSibling = currentElement.previousElementSibling;
console.log('Previous Sibling:', prevSibling ? prevSibling.id : 'None');
How it works: This snippet demonstrates various properties for navigating the DOM tree. `parentNode` gives you the immediate parent of an element. `children` returns an HTMLCollection of all direct child elements. `firstElementChild` and `lastElementChild` provide quick access to the first and last direct children, respectively. `nextElementSibling` and `previousElementSibling` allow you to move horizontally through the DOM, accessing adjacent elements at the same level. These properties are essential for locating and interacting with elements relative to a known starting point.