dom_dom0200_004

要素ノードのみを辿りたいときは、「最初の子要素」には ( A )、「次の兄弟要素」には ( B ) を使う。

解答

A: firstElementChild
B: nextElementSibling

解説

firstElementChild と nextElementSibling は「要素ノード」に限定して移動するAPI。テキストやコメントをスキップできるため、DOM操作が安定する。

使用例(サンプルコード)

[ js ]

const ul = document.querySelector('ul');
const firstLi = ul.firstElementChild;
console.log(firstLi.tagName); // "LI"
console.log(firstLi.nextElementSibling?.tagName); // 次のLIなど