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備忘録】document.getElementById の使い方徹底解説

Posted at

1. document.getElementById とは?

document.getElementById は、HTML 要素の ID を指定して要素を取得するメソッド です。

ポイント:指定した id に一致する 最初の要素 を取得する。


2. 基本的な使い方

const element = document.getElementById("myElement");
  • myElement:取得したい要素の id を指定
  • element:取得した要素(null の場合もある)

☑️ 例1:要素を取得してテキストを変更

const heading = document.getElementById("title");
heading.textContent = "新しいタイトル";

ID title の要素のテキストを変更


3. 取得した要素の操作

☑️ 例2:CSS スタイルを変更

const box = document.getElementById("box");
box.style.backgroundColor = "lightblue";

ID box の背景色を変更

☑️ 例3:クリックイベントを追加

const button = document.getElementById("btn");
button.addEventListener("click", () => {
    alert("ボタンがクリックされました!");
});

ID btn のボタンをクリックするとアラートが表示


4. getElementById の注意点

☑️ 取得できない場合(null になる)

const nonExistent = document.getElementById("notFound");
console.log(nonExistent); // null

ID notFound が存在しないと null が返る

☑️ 要素が null のときの対処

const element = document.getElementById("myElement");
if (element) {
    element.textContent = "見つかった!";
} else {
    console.log("要素が見つかりません");
}

要素が存在するかチェックしてから操作する


5. querySelector との違い

document.getElementByIdid による 直接検索 に特化していますが、
querySelectorCSS セレクターを利用 できます。

🔍 getElementById vs querySelector

メソッド 概要
document.getElementById("id名") id による 高速な要素取得(単一要素)
document.querySelector("#id名") CSS セレクター を使用(より柔軟)

☑️ 例4:querySelector を使った場合

const element = document.querySelector("#myElement");

CSS セレクターを使用して ID を取得する方法


6. まとめ

☑️ document.getElementById("id") を使うと、ID から要素を取得できる
☑️ 存在しない ID を指定すると null になるので注意
☑️ styletextContent で要素の変更が可能
☑️ querySelector("#id") との違いを理解する

getElementById を活用して、DOM 操作をスムーズに行おう!

0
0
3

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?