定義と使い方
id属性の値はHTML内で一意である必要があるため、この関数を使用すると要素をすばやく取得できます。
基本例
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>getElementById()の例</title>
</head>
<body>
<p id="hello">ようこそ。お会いできてうれしいです!</p>
<script>
const changeColor = newColor => {
const ele = document.getElementById("hello"); // id="hello"と一致する要素を取得します。
ele.style.color = newColor;
}
</script>
<button type="button" onclick="changeColor('red');">赤色に変える</button>
<button type="button" onclick="changeColor('blue');">青色に変える</button>
</body>
</html>
ようこそ。お会いできてうれしいです!
構文
document.getElementById(id);
引数
id |
探している要素のid属性の値です。この値は大文字と小文字を区別する文字列です。 |
|---|
戻り値
注意点
getElementById()関数を使用する際には、いくつか注意点があります。
探している要素がない場合のエラーを防ぐ
getElementById()関数で探している要素がない場合は、nullを返します。
次のような例では、エラーが発生します。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>探している要素がない場合にエラーが発生する例</title>
</head>
<body>
<button type="button" id="btn1">btn1ボタン</button>
<button type="button" id="btn2">btn2ボタン</button>
<button type="button" id="btn3">btn3ボタン</button>
<script>
/* id="btn-4"の要素はありません。 */
const eleBtn4 = document.getElementById("btn-4"); // id="btn-4"と一致する要素を取得します。
// eleBtn4は要素オブジェクトではなくnullになります。
// Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
eleBtn4.addEventListener("click", () => {
// ...
});
</script>
</body>
</html>
ボタンをクリックしたときに発生するイベントを受け取るためのイベントリスナー関数であるaddEventListener()は、イベントをサポートするオブジェクト(例えば、要素オブジェクトやDocument、windowオブジェクトなど)を対象とします。しかし、nullはイベントをサポートするオブジェクトではないため、TypeErrorが発生します。
このような状況は、よく起こる可能性があります。例では、HTML文書内にHTML要素とJavaScriptをインラインで記述しているため、HTML要素とJavaScriptの関係を一目で確認できます。しかし、JavaScriptをファイルに分離して記述する場合は、このような問題が発生することがあります。開発者がHTML要素とJavaScriptの関係を一目で把握することが難しくなるためです。
このようなエラーが発生する可能性がある状況に備えて、次のようにコードを記述しておくと、エラーの発生を防ぐのに役立ちます。
if()文
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>探している要素がない場合にエラーが発生する例</title>
</head>
<body>
<button type="button" id="btn1">btn1ボタン</button>
<button type="button" id="btn2">btn2ボタン</button>
<button type="button" id="btn3">btn3ボタン</button>
<script>
/* id="btn-4"の要素はありません。 */
const eleBtn4 = document.getElementById("btn-4"); // id="btn-4"と一致する要素を取得します。
// eleBtn4は要素オブジェクトではなくnullになります。
if (eleBtn4) {
eleBtn4.addEventListener("click", () => {
// ...
});
} else {
console.warn("idが「btn-4」の要素を取得できません。");
}
</script>
</body>
</html>
この例では、変数eleBtn4がnullかどうかをif()文で評価し、trueの場合はコードを実行し、falseの場合はコンソールに警告メッセージを出力するようにしています。
if()文の代わりにtry..catch文を使用することもできます。
try..catch文
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>探している要素がない場合にエラーが発生する例</title>
</head>
<body>
<button type="button" id="btn1">btn1ボタン</button>
<button type="button" id="btn2">btn2ボタン</button>
<button type="button" id="btn3">btn3ボタン</button>
<script>
/* id="btn-4"の要素はありません。 */
const btn4 = document.getElementById("btn-4"); // id="btn-4"と一致する要素を取得します。
// btn4は要素オブジェクトではなくnullになります。
try {
btn4.addEventListener("click", () => {
// ...
});
} catch (error) {
console.warn("idが「btn-4」の要素を取得できません。");
}
</script>
</body>
</html>
try..catch文を使用することもできますが、一般的にはif()文で戻り値がnullかどうかを確認する方法のほうが推奨されます。エラーが発生してから対処するよりも、エラーが発生する前にあらかじめ防ぐことができるためです。
探している要素のid属性の値は大文字と小文字を区別する
getElementById(id)関数の引数idは、大文字と小文字を区別する文字列です。
<div id="user-id"></div>
idは大文字と小文字を区別する文字列です。
getElementById("User-id");
getElementById("User-Id");
getElementById("USER-ID");
idは大文字と小文字が完全に一致している必要があります。
getElementById("user-id");
getElementById()はdocumentオブジェクトのメソッドだけ
getElementById()は、HTML文書全体を対象として要素を探すdocument専用のメソッドです。そのため、parentNodeやparentElementプロパティ(Property)を介してアクセスできるElementオブジェクトでは使用できません。
<div id="container">
<div id="child"></div>
</div>
Elementオブジェクトでは使用できません。
const container = document.getElementById("container");
// idが一致する要素を探してElementオブジェクトを返します。
// 「container」は「documentオブジェクト」ではなく「Elementオブジェクト」です。
// Uncaught TypeError: container.getElementById is not a function
const child = container.getElementById("child");
getElementById()は、documentオブジェクトでのみ使用できるメソッドです。
const child = document.getElementById("child");
ブラウザーの互換性
| メソッド |
デスクトップ Chrome
|
デスクトップ Edge
|
デスクトップ Firefox
|
Safari
|
|---|---|---|---|---|
getElementById()
|
1 | 12 | 1 | 1 |
仕様書
| 仕様書 | |
|---|---|
getElementById()
|
DOM Standard #ref-for-dom-nonelementparentnode-getelementbyid② |