JAVASCRIPT

Traverse and Manipulate Sibling DOM Elements

Learn how to navigate between sibling elements in the DOM using `previousElementSibling` and `nextElementSibling` to apply changes or retrieve information efficiently.

document.addEventListener('DOMContentLoaded', () => {
  const firstItemButton = document.getElementById('firstItemButton');

  if (firstItemButton) {
    firstItemButton.addEventListener('click', () => {
      const listItem = firstItemButton.closest('li'); // Get the parent li
      if (listItem) {
        // Manipulate the current item
        listItem.style.backgroundColor = '#f0f8ff'; // Alice Blue
        console.log(`Current item: ${listItem.textContent}`);

        // Get and manipulate the next sibling
        const nextSibling = listItem.nextElementSibling;
        if (nextSibling) {
          nextSibling.style.fontWeight = 'bold';
          nextSibling.style.color = 'darkgreen';
          console.log(`Next sibling: ${nextSibling.textContent}`);
        }

        // Get and manipulate the previous sibling
        const prevSibling = listItem.previousElementSibling;
        if (prevSibling) {
          prevSibling.style.textDecoration = 'underline';
          prevSibling.style.color = 'darkred';
          console.log(`Previous sibling: ${prevSibling.textContent}`);
        }
      }
    });
  }
});

// HTML structure for this example:
// <ul id="siblingList">
//   <li>Item A</li>
//   <li id="startItem">Item B <button id="firstItemButton">Highlight Siblings</button></li>
//   <li>Item C</li>
//   <li>Item D</li>
// </ul>
How it works: This snippet demonstrates how to traverse sibling elements using `previousElementSibling` and `nextElementSibling`. Starting from a reference element (e.g., the parent `<li>` of a clicked button), you can easily access and manipulate adjacent elements without needing to query the entire document, which is useful for tasks like highlighting or updating related list items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs