function findRelatedElement(startElementId, relationship, selector = null) { const startElement = document.getElementById(startElementId); if (!startElement) { console.error(`Starting element with ID '${startElementId}' not found.`); return null; } switch (relationship) { case 'parent': return startElement.parentElement; case 'closest': if (!selector) { console.error('Selector is required for 'closest' relationship.'); return null; } return startElement.closest(selector); case 'children': // Returns a live HTMLCollection return Array.from(startElement.children); case 'first-child': return startElement.firstElementChild; case 'last-child': return startElement.lastElementChild; case 'next-sibling': return startElement.nextElementSibling; case 'prev-sibling': return startElement.previousElementSibling; default: console.warn('Invalid relationship. Use parent, closest, children, first-child, last-child, next-sibling, or prev-sibling.'); return null; } } // Example usage: //
// //
const parent = findRelatedElement('currentItem', 'parent'); console.log('Parent:', parent ? parent.id : 'N/A'); // myList const closestContainer = findRelatedElement('currentItem', 'closest', '.container'); console.log('Closest container:', closestContainer ? closestContainer.className : 'N/A'); // container const childrenOfList = findRelatedElement('myList', 'children'); console.log('Children of myList:', childrenOfList.map(c => c.textContent)); // ["Item A", "Item B", "Item C"] const nextSibling = findRelatedElement('currentItem', 'next-sibling'); console.log('Next sibling:', nextSibling ? nextSibling.textContent : 'N/A'); // Item C