JAVASCRIPT
Traverse the DOM Tree (Parents, Children, Siblings)
Understand how to programmatically traverse the Document Object Model to find parent, child, and sibling elements, enabling precise manipulation based on relationships.
function domTraverse(elementId) {
const element = document.getElementById(elementId);
if (!element) {
console.error('Element not found:', elementId);
return {};
}
console.log(`
--- Traversing from element #${elementId} ---`);
// Parent elements
const parent = element.parentNode;
console.log('Parent Node:', parent ? parent.nodeName : 'N/A');
const closestArticle = element.closest('article');
console.log('Closest <article> ancestor:', closestArticle ? closestArticle.id || closestArticle.nodeName : 'N/A');
// Child elements
console.log('Child Elements (Live HTMLCollection):', element.children);
Array.from(element.children).forEach((child, index) => {
console.log(`- Child ${index + 1}: ${child.nodeName} ${child.id ? '#' + child.id : ''}`);
});
const firstChild = element.firstElementChild;
console.log('First Child Element:', firstChild ? firstChild.nodeName : 'N/A');
const lastChild = element.lastElementChild;
console.log('Last Child Element:', lastChild ? lastChild.nodeName : 'N/A');
const specificChildren = element.querySelectorAll('.item');
console.log('Specific children with class "item" (NodeList):', specificChildren);
specificChildren.forEach((child, index) => {
console.log(`- Item ${index + 1}: ${child.nodeName} ${child.textContent}`);
});
// Sibling elements
const previousSibling = element.previousElementSibling;
console.log('Previous Sibling Element:', previousSibling ? previousSibling.nodeName : 'N/A');
const nextSibling = element.nextElementSibling;
console.log('Next Sibling Element:', nextSibling ? nextSibling.nodeName : 'N/A');
return {
parent,
closestArticle,
children: Array.from(element.children),
firstChild,
lastChild,
specificChildren: Array.from(specificChildren),
previousSibling,
nextSibling,
};
}
// Usage example:
// <article id="mainArticle">
// <section id="sectionA">
// <h2>Section A</h2>
// <ul id="myList">
// <li>Item 1</li>
// <li id="targetElement" class="item">Item 2 (Target)</li>
// <li>Item 3</li>
// </ul>
// </section>
// <p>Some other content</p>
// </article>
domTraverse('targetElement');
How it works: This snippet illustrates various methods for navigating the DOM tree relative to a specified element. It covers finding an element's immediate `parentNode` and its closest ancestor matching a CSS selector (`closest()`). It also demonstrates how to access all `children` elements, the `firstElementChild`, `lastElementChild`, and specific children using `querySelectorAll()`. Additionally, it shows how to locate `previousElementSibling` and `nextElementSibling` to move horizontally through the DOM.