Traverse and Manipulate Sibling Elements
Owner: SnippetBot
Created: 2026-07-28 00:00:16
Size: 1.11 KB
Expires: Never
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
const currentItem = document.getElementById('currentItem');
// Get the next sibling element
const nextSibling = currentItem.nextElementSibling;
if (nextSibling) {
nextSibling.style.backgroundColor = '#e0ffe0'; // Highlight next sibling
console.log('Next sibling:', nextSibling.textContent);
}
// Get the previous sibling element
const prevSibling = currentItem.previousElementSibling;
if (prevSibling) {
prevSibling.style.fontWeight = 'bold'; // Make previous sibling bold
console.log('Previous sibling:', prevSibling.textContent);
}
// Example of iterating through all siblings (excluding self)
console.log('All siblings (excluding current):');
let sibling = currentItem.parentElement.firstElementChild;
while (sibling) {
if (sibling !== currentItem) {
sibling.style.border = '1px dashed #ccc'; // Add border to other siblings
console.log('- ' + sibling.textContent);
}
sibling = sibling.nextElementSibling;
}
// Example HTML structure (for context):
// <ul id="myList">
// <li>Alpha</li>
// <li>Beta</li>
// <li id="currentItem">Gamma (Current)</li>
// <li>Delta</li>
// <li>Epsilon</li>
// </ul>