JAVASCRIPT
Efficiently Traverse and Manipulate Sibling DOM Elements
Learn to navigate between sibling HTML elements using `previousElementSibling`, `nextElementSibling`, and `children` properties to apply changes or retrieve information within a specific parent.
const targetItem = document.getElementById('item-2');
if (targetItem) {
console.log('Target item:', targetItem.textContent);
// Get the immediately preceding sibling element
const prevSibling = targetItem.previousElementSibling;
if (prevSibling) {
console.log('Previous sibling:', prevSibling.textContent);
prevSibling.style.backgroundColor = '#e0f7fa'; // Light blue
}
// Get the immediately succeeding sibling element
const nextSibling = targetItem.nextElementSibling;
if (nextSibling) {
console.log('Next sibling:', nextSibling.textContent);
nextSibling.style.fontWeight = 'bold';
}
// Get all sibling elements (excluding itself)
// One way: get parent, then all children, filter self
const parent = targetItem.parentNode;
if (parent) {
Array.from(parent.children).forEach(child => {
if (child !== targetItem) {
child.classList.add('sibling-style');
}
});
}
}
/*
Example HTML and CSS:
<style>
.sibling-style {
padding: 5px;
margin-bottom: 5px;
border: 1px solid #ccc;
}
</style>
<div id="container">
<div id="item-1">Item One</div>
<div id="item-2">Item Two (Target)</div>
<div id="item-3">Item Three</div>
<div id="item-4">Item Four</div>
</div>
*/
How it works: This snippet demonstrates how to navigate and manipulate sibling elements within the DOM. `previousElementSibling` and `nextElementSibling` provide direct access to the adjacent siblings, allowing for targeted modifications. To affect all siblings, the code shows a common pattern: getting the `parentNode`, iterating through its `children` collection, and then applying changes to each child while potentially excluding the original target element. This is crucial for creating dynamic, interconnected UI components.