JAVASCRIPT
Update Sibling Element's Content on Event
Discover how to navigate the DOM to find and update a specific sibling element's content based on an event trigger, crucial for building dynamic and interconnected UI components.
document.querySelectorAll('.trigger-button').forEach(button => {
button.addEventListener('click', function() {
const targetSiblingClass = this.getAttribute('data-target-sibling');
const newText = this.getAttribute('data-new-text') || 'Content Updated!';
let sibling = this.nextElementSibling; // Start with the next sibling
// Loop through siblings to find the one with the target class
while (sibling) {
if (sibling.classList.contains(targetSiblingClass)) {
sibling.textContent = newText;
console.log(`Updated sibling with class '${targetSiblingClass}' to: '${newText}'`);
return; // Found and updated, exit
}
sibling = sibling.nextElementSibling;
}
console.warn(`No sibling with class '${targetSiblingClass}' found.`);
});
});
// Example usage:
// <div class="container">
// <button class="trigger-button" data-target-sibling="status-message" data-new-text="Status: Active">Activate</button>
// <p class="status-message">Status: Inactive</p>
// </div>
// <div class="container">
// <button class="trigger-button" data-target-sibling="output-area" data-new-text="Data Loaded!">Load Data</button>
// <div class="output-area">No data yet.</div>
// </div>
How it works: This snippet illustrates DOM traversal by finding and updating a specific sibling element based on a click event. It attaches an event listener to multiple buttons, then uses `nextElementSibling` and a loop to iterate through subsequent siblings until a matching class name (specified via a `data-target-sibling` attribute) is found. Once found, the sibling's `textContent` is updated, enabling localized and dynamic UI changes.