LoginSignup
1
0

More than 3 years have passed since last update.

getElementsByClassNameとgetElemetByIdの違い

Posted at

ネイティブJSでのDOM操作を学習中にgetElementsByClassNameとgetElemetByIdで大きな違いがあることを発見したのでメモ書きです。

やりたいこと

以下のHTMLコードでulタグの子要素の数を把握する。

  <ul class="list">
    <li>apple</li>
    <li>orange</li>
    <li>melon</li>
  </ul>

jQueryで実装すると

$(function(){
  alert($('.list').children().length);
})

これで「3」が返ってくる。

getElemetsByClassNameで実装

const List = document.getElementsByClassName('list');

const num = List.childElementCount;
alert(num);

この場合undefindが返ってくる。
console.log('list') を確認すると「ul.list」となっている。

HTMLCollection [ul.list]
0: ul.list
length: 1
__proto__: HTMLCollection

getElemetByIdで実装

const List = document.getElementsById('list');

const num = List.childElementCount;
alert(num);

この場合は「3」が返ってきて、思い通りに実装できる。
console.log('list')を確認すると次のとおり。

<ul id="list">
  <li>apple</li>
  <li>orange</li>
  <li>melon</li>
</ul>

なぜこのような結果に?

現段階でこのような結果になる理由がわかりません。
もう少し深掘りしてみて、わかったことを追記しようと思います。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0