nextSibling と previousSibling は、兄弟ノードを取得するプロパティです。同様に nextElementSibling と previousElementSibling もあります。
4つのプロパティ
| プロパティ | 取得対象 |
|---|---|
| nextSibling | 次の兄弟ノード(テキスト含む) |
| previousSibling | 前の兄弟ノード(テキスト含む) |
| nextElementSibling | 次の兄弟要素(Element のみ) |
| previousElementSibling | 前の兄弟要素(Element のみ) |
使い方
<ul> <li id="item1">項目1</li> <li id="item2">項目2</li> <li id="item3">項目3</li> </ul>
const item2 = document.getElementById('item2'); // nextSibling はテキストノード(改行)かもしれない console.log(item2.nextSibling); // #text // nextElementSibling は確実に Element console.log(item2.nextElementSibling); // <li id="item3"> // previousElementSibling も同様 console.log(item2.previousElementSibling); // <li id="item1">
兄弟がいない場合
先頭や末尾の要素で、それ以上兄弟がない場合は null を返します。
const item1 = document.getElementById('item1'); console.log(item1.previousElementSibling); // null(前に兄弟がいない) const item3 = document.getElementById('item3'); console.log(item3.nextElementSibling); // null(次に兄弟がいない)
実際に動かしてみよう
リスト項目を上下に移動させます。
HTML
CSS
JavaScript
<ul id="list"> <li>項目A</li> <li class="selected">項目B(選択中)</li> <li>項目C</li> <li>項目D</li> </ul> <button id="upBtn">↑ 上へ</button> <button id="downBtn">↓ 下へ</button>
#list li { padding: 8px; } .selected { background: #4caf50; color: white; }
document.getElementById('upBtn').addEventListener('click', () => { const selected = document.querySelector('.selected'); const prev = selected.previousElementSibling; if (prev) { selected.parentElement.insertBefore(selected, prev); } }); document.getElementById('downBtn').addEventListener('click', () => { const selected = document.querySelector('.selected'); const next = selected.nextElementSibling; if (next) { selected.parentElement.insertBefore(next, selected); } });
すべての兄弟をループする
const start = document.getElementById('item1'); // 後ろの兄弟をすべて取得 let current = start; while (current.nextElementSibling) { current = current.nextElementSibling; console.log(current.textContent); }
どれを使うべきか
nextSibling / previousSibling
テキストノードも含む。通常は使わない
nextElementSibling / previousElementSibling
Element だけを返す。こちらを使う
通常は nextElementSibling / previousElementSibling を使いましょう。テキストノードが返ってきて困ることがありません。