JavaScriptのgetElementById()でIDから要素を取得する
document.getElementById("notice")はIDが正確にnoticeの要素を返します。大文字と小文字を区別し、一致しなければnullです。CSSセレクターと違い、IDに#を付けません。
ID文字列で要素を一つ選ぶ
const notice = document.getElementById("notice");
if (notice !== null) {
notice.textContent = "처리가 완료되었습니다.";
}
getElementById()の戻り値はDOM(Document Object Model)の要素です。文字列はtextContentで読みます。メソッド名の末尾はIdです。通常の親要素にはこのメソッドがありません。
検索・変更・復元の完全な例
実習をUTF-8のget-element-by-id.htmlとして保存し、開きます。ライブラリーは不要です。スクリプトはボタンや出力先の後ろにあります。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Find an element by ID</title>
</head>
<body>
<h1>Find an element by ID</h1>
<p id="notice">Initial notice</p>
<label for="lookup-id">ID to find</label>
<select id="lookup-id">
<option value="notice">notice</option>
<option value="Notice">Notice</option>
<option value="#notice">#notice</option>
<option value="missing">missing</option>
</select>
<button id="find" type="button">Find</button>
<button id="change" type="button">Change notice</button>
<button id="restore" type="button">Restore</button>
<pre id="output"></pre>
<script>
const notice = document.getElementById("notice");
const selectedId = document.getElementById("lookup-id");
const output = document.getElementById("output");
function findElement() {
const element = document.getElementById(selectedId.value);
if (element === null) {
output.textContent = "Element not found.";
return;
}
output.textContent = `Tag: ${element.tagName}\nText: ${element.textContent}`;
}
document.getElementById("find").addEventListener("click", findElement);
document.getElementById("change").addEventListener("click", () => {
notice.textContent = "Updated notice";
findElement();
});
document.getElementById("restore").addEventListener("click", () => {
notice.textContent = "Initial notice";
selectedId.value = "notice";
findElement();
});
findElement();
</script>
</body>
</html>
最初はTag: PとText: Initial noticeが出ます。Change noticeで同じ要素の文字を変えます。Noticeまたは#noticeを選んでFindを押すと見つかりません。Restoreで戻せます。nullの場合はプロパティを読む前に関数が終了します。
要素があるはずなのにnullになる場合
実際のidと引数を比べ、大文字・小文字と空白を確認します。nameやclassだけでは一致しません。早すぎる実行を避けるには、スクリプトを要素の後ろに置くか、外部の通常のscriptにdeferを付けます。インラインでは同じ効果がありません。createElement()で作った要素は文書に入れるまで見つかりません。
<script src="app.js" defer></script>
IDの重複と他の選択方法
IDは重複させません。重複するとツリー順の最初が返ります。繰り返すカードにはクラスを使えます。querySelector()はCSS条件で最初の一致、querySelectorAll()はすべての一致を返します。取得した文字の変更はinnerText, innerHTML, textContentで確認できます。
const one = document.querySelector("#notice");
const cards = document.querySelectorAll(".card");
文書断片でコロンを含むIDを検索する
実習ページのConsoleで実行します。直接検索にはresult:2026をそのまま使います。コロンはCSSで特別な意味を持つため、セレクターを作る場合はCSS.escape()でIDを変換してから#を付けます。
{
const fragment = document.createDocumentFragment();
const title = document.createElement("p");
title.id = "result:2026";
fragment.append(title);
console.log(fragment.getElementById(title.id) === title); // true
console.log(fragment.querySelector("#" + CSS.escape(title.id)) === title); // true
console.log(document.getElementById(title.id) === null); // true in the example
}
3行ともtrueです。最初の二つはDocumentFragment内に見つかります。文書に挿入していないため、文書からの検索には出ません。すでに要素を参照する変数があれば、その変数を直接使えます。




