0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】DOM要素の取得メソッド ~get Element By~

Last updated at Posted at 2025-10-31

DOM 要素の取得方法の違い

DOM 要素を取得する3つの主要なメソッドについて、それぞれの特徴と違いを説明します。

3つのメソッドの比較

1. getElementById

取得基準: ID属性
戻り値: 単一の要素(Element)または null

const element = document.getElementById('mainheading');
// <h1 id="mainheading">を取得

特徴

  • IDは1つのHTML文書内で一意である必要があるため、必ず1つの要素のみを返します
  • 該当する要素が存在しない場合は null を返します
  • 3つの中で最も高速に動作します

2. getElementsByTagName

取得基準: HTMLタグ名
戻り値: HTMLCollection(複数要素のコレクション)

const images = document.getElementsByTagName('img');
// ページ内の全ての<img>要素を取得

特徴

  • 指定したタグ名の要素をすべて取得します
  • 戻り値は配列のようなオブジェクト(HTMLCollection)です
  • 要素が1つでも、0個でも、常にHTMLCollectionを返します
// 最初の要素にアクセスする場合
const firstImage = images[0];

// すべての要素を処理する場合
for (let i = 0; i < images.length; i++) {
    console.log(images[i]);
}

3. getElementsByClassName

取得基準: class属性
戻り値: HTMLCollection(複数要素のコレクション)

const items = document.getElementsByClassName('menu-item');
// class="menu-item" を持つすべての要素を取得

特徴

  • 指定したクラス名を持つ要素をすべて取得します
  • 戻り値は HTMLCollection です
  • 1つの要素が複数のクラスを持つ場合でも、指定したクラスを含んでいれば取得されます
// 複数のクラス名を持つ要素も取得可能
// <div class="menu-item active"> → 取得される

戻り値の違いを理解する

最も重要な違いは戻り値の型ですね。

実際の使用例

<div id="container">コンテナ</div>
<p class="text">テキスト1</p>
<p class="text">テキスト2</p>
<img src="image1.jpg">
<img src="image2.jpg">
// getElementById - 単一要素を直接取得
const container = document.getElementById('container');
container.style.color = 'red'; // 直接操作できる

// getElementsByClassName - コレクションを取得
const texts = document.getElementsByClassName('text');
texts[0].style.color = 'blue'; // インデックスでアクセス
texts[1].style.color = 'green';

// getElementsByTagName - コレクションを取得
const images = document.getElementsByTagName('img');
console.log(images.length); // 2

使い分けのポイント

メソッド 使用場面
getElementById 特定の1つの要素を取得したい時
getElementsByTagName 特定のタグの要素をすべて取得したい時
getElementsByClassName 特定のクラスを持つ要素をすべて取得したい時

注意点: getElementsByTagNamegetElementsByClassName は名前に s (Elements) が付いていることに注目してください。複数形になっているのは、複数の要素を返すことを示しています。

まとめ

  • getElementById: ID で単一要素を取得、最も高速
  • getElementsByTagName: タグ名で複数要素を取得、HTMLCollection を返す
  • getElementsByClassName: クラス名で複数要素を取得、HTMLCollection を返す

複数要素を取得するメソッドは、たとえ該当する要素が1つしかなくても HTMLCollection を返すため、インデックスを使ってアクセスする必要があります。この違いを理解することで、適切なメソッドを選択できるようになります。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?