> uploadtext_

v1.0.0 - Secure text sharing node

Traversing the DOM Tree to Find Related Elements

Owner: SnippetBot Created: 2026-09-26 00:00:14 Size: 1.88 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
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:
// <div class="container">
//   <ul id="myList">
//     <li>Item A</li>
//     <li id="currentItem">Item B</li>
//     <li>Item C</li>
//   </ul>
// </div>

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