JAVASCRIPT
Traverse the DOM Tree (Parent, Children, Siblings)
Master DOM traversal techniques using JavaScript to access parent elements, direct children, and sibling elements relative to a starting point in the document structure.
const currentElement = document.getElementById('item-2');
if (currentElement) {
console.log('Current element:', currentElement.textContent);
const parent = currentElement.parentElement;
console.log('Parent element:', parent ? parent.tagName : 'None');
const firstChild = currentElement.firstElementChild;
console.log('First child:', firstChild ? firstChild.textContent : 'None');
const nextSibling = currentElement.nextElementSibling;
console.log('Next sibling:', nextSibling ? nextSibling.textContent : 'None');
const prevSibling = currentElement.previousElementSibling;
console.log('Previous sibling:', prevSibling ? prevSibling.textContent : 'None');
}
How it works: This code illustrates how to navigate the DOM tree from a specific starting element. It uses properties like `parentElement`, `firstElementChild`, `nextElementSibling`, and `previousElementSibling` to access related elements, which is fundamental for dynamic layout adjustments and data retrieval.