JAVASCRIPT
Navigate the DOM with Parent and Sibling Properties
Efficiently traverse the Document Object Model (DOM) using JavaScript's `parentNode`, `nextElementSibling`, `previousElementSibling`, and `children` properties to locate related elements.
<ul id="myList">
<li>Item One</li>
<li id="targetItem">Item Two</li>
<li>Item Three</li>
</ul>
<script>
const targetElement = document.getElementById('targetItem');
// Get the direct parent element
const parent = targetElement.parentNode;
console.log('Parent element tag:', parent.tagName); // UL
// Get the next sibling element (skips text nodes)
const nextSibling = targetElement.nextElementSibling;
if (nextSibling) {
console.log('Next sibling text:', nextSibling.textContent); // Item Three
}
// Get the previous sibling element (skips text nodes)
const prevSibling = targetElement.previousElementSibling;
if (prevSibling) {
console.log('Previous sibling text:', prevSibling.textContent); // Item One
}
// Get all direct child elements of the parent
const childrenOfParent = parent.children; // Returns an HTMLCollection
console.log('Children of parent:');
Array.from(childrenOfParent).forEach(child => {
console.log('- ' + child.textContent);
});
</script>
How it works: This snippet demonstrates fundamental DOM traversal properties, allowing you to navigate the hierarchical structure of HTML elements. `parentNode` returns the direct parent of a given element. `nextElementSibling` and `previousElementSibling` provide access to adjacent sibling elements, automatically ignoring text nodes and comments. `children` returns an `HTMLCollection` of all direct child *elements* (not including text or comment nodes). These properties are indispensable for dynamic interactions and manipulations within complex DOM structures.