レッスンに戻る

DOM の子

重要度:5

このページを見てください:

<html>
<body>
  <div>Users:</div>
  <ul>
    <li>John</li>
    <li>Pete</li>
  </ul>
</body>
</html>

次の各要素にアクセスする方法を少なくとも 1 つ挙げてください:

  • <div> DOM ノード
  • <ul> DOM ノード
  • 2 番目の <li>(ピート)

たとえば、次のような方法が多数あります。

<div> DOM ノード

document.body.firstElementChild
// or
document.body.children[0]
// or (the first node is space, so we take 2nd)
document.body.childNodes[1]

<ul> DOM ノード

document.body.lastElementChild
// or
document.body.children[1]

2 番目の <li>(ピート)

// get <ul>, and then get its last element child
document.body.lastElementChild.lastElementChild