JAVASCRIPT

Traversing and Manipulating DOM Sibling Elements

Explore methods to traverse the DOM horizontally using JavaScript, finding and manipulating previous and next sibling elements of a given node, useful for list interactions or related content.

function highlightSibling(elementId, direction = 'next') {
  const element = document.getElementById(elementId);
  if (!element) {
    console.error(`Element with ID '${elementId}' not found.`);
    return;
  }

  let sibling;
  if (direction === 'next') {
    sibling = element.nextElementSibling;
  } else if (direction === 'prev') {
    sibling = element.previousElementSibling;
  } else {
    console.warn('Invalid direction. Use "next" or "prev".');
    return;
  }

  if (sibling) {
    // Remove highlight from all siblings first (optional, for single highlight)
    Array.from(element.parentElement.children).forEach(child => {
      child.classList.remove('highlight-sibling');
    });
    sibling.classList.add('highlight-sibling');
    console.log(`Highlighted ${direction} sibling:`, sibling.textContent);
  } else {
    console.log(`No ${direction} sibling found for ${element.textContent}`);
  }
}

// Example HTML structure:
// <ul id="myList">
//   <li>Item A</li>
//   <li id="currentItem">Item B</li>
//   <li>Item C</li>
//   <li>Item D</li>
// </ul>

// Call to highlight the next sibling of 'currentItem'
highlightSibling('currentItem', 'next');

// Call to highlight the previous sibling of 'currentItem' after a delay
setTimeout(() => {
  highlightSibling('currentItem', 'prev');
}, 2000);

// CSS for highlight-sibling class
// .highlight-sibling { background-color: yellow; }
How it works: This snippet demonstrates how to navigate between sibling elements in the DOM using `nextElementSibling` and `previousElementSibling`. These properties return the immediate next or previous sibling node that is an element (ignoring text and comment nodes). It's useful for scenarios like creating 'next/previous' buttons in a carousel, highlighting items in a list relative to a selected one, or organizing dynamic content where elements are logically related horizontally within their parent.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs