JavaScript
🚨 TypeError: Cannot read properties of null(null参照)
nullのプロパティにアクセスしている
😰 こんな症状
nullに対して.や[]でアクセスするとエラーになる。DOM要素の取得失敗で起きやすいよ。
🔍 原因
querySelectorやgetElementByIdの結果がnull(要素が見つからない)なのに、そのままプロパティにアクセスしているよ。JavaScriptではnullやundefinedのプロパティにアクセスするとTypeErrorが発生するんだ。
❌ エラーが起きるコード
const user = null;
console.log(user.name);
// null のプロパティ ✅ 直し方
1. if (element !== null)で存在確認してからアクセスする。 2. オプショナルチェーン(?.)を使う:element?.textContent。 3. nullが返る原因(IDミス、DOM未構築等)を根本的に修正する。 4. console.log(element)でnullかどうか確認する。
✅ 修正後のコード
const user = null;
console.log(user?.name);
// オプショナルチェーン この解決法は役立ちましたか?
🔗 関連するエラー
- Uncaught TypeError: Cannot read properties of null — getElementById の id が存在しない
- TypeError: Cannot read properties of undefined (reading 'length') — undefinedに対して.lengthを呼んでいる
- TypeError: Cannot set properties of null (setting 'textContent') — nullに対してプロパティを設定しようとしている
- ボタンを押しても何も起きない — getElementById の id 不一致
- ReferenceError: Cannot access before initialization — let/constの宣言前にアクセスしている
🔗 別カテゴリの関連エラー
📖 この問題を学べるレッスン
📝 関連ブログ記事
- プログラミングのエラーメッセージの読み方 — エラーの読み方を基礎から解説
- JavaScriptとは?初心者向けにわかりやすく解説 — 変数・関数・イベントの基本
- JavaScriptでボタンクリックを動かす方法 — ボタンクリック時の動作を解説