JavaScript
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
取得しようとしたHTML要素が見つかっていない
こんな症状
addEventListenerやtextContentを使った行で「Cannot read properties of null」と出る。getElementByIdなどが要素を見つけられずnullを返しているのが原因だよ。
まず試す
JSの id 文字列と HTML の id 属性を完全一致させ、<script> を body の閉じタグ直前に置く(または defer)。
js
<button id="send-btn">送信</button>
<script>
const el = document.getElementById("send-btn");
el.addEventListener("click", () => alert("送信"));
</script>これで直らなければ、下の「自分のケース」を確認。
🔍 自分のケースはどれ?
- ✓id名が少し違う(sendBtn と send-btn など)
→ 大文字小文字・ハイフンも別物。HTMLの id をコピペしてJSに貼る。 - ✓script が要素より前にある
→ <script> を body の閉じタグ直前へ。または defer 属性を付ける。 - ✓reading が textContent や style でも同じ
→ 原因と直し方は同じ。要素がちゃんと取れているか確認する。
なぜ起きる?
document.getElementById('xxx')で指定したidがHTMLに存在しないよ。ブラウザはidが見つからないとnullを返すんだ。そのnullに対して.addEventListener()や.textContentなどのプロパティを読もうとするとこのエラーが出るよ。原因はほぼ2つ:(1) idのタイポ(大文字小文字・ハイフンの違いも別物)、(2) <script>がHTML要素より前にあって、要素が作られる前にJSが実行されている。reading の部分が 'textContent' や 'value' や 'style' でも原因と直し方は同じだよ。
✕ エラーが起きるコード
<button id="send-btn">送信</button>
<script>
// ❌ scriptが要素より前にある or idが違うと null になる
const el = document.getElementById("sendBtn");
el.addEventListener("click", () => alert("送信"));
// Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
</script>✓ 直したコード
<button id="send-btn">送信</button>
<script>
// ✅ HTMLのidと同じ文字列を指定し、scriptは要素の後に置く
const el = document.getElementById("send-btn");
el.addEventListener("click", () => alert("送信"));
</script>✅ 直ったか確認
console.log(document.getElementById('id名')) が要素を表示し、エラーが消えればOK。
この解決法は役立ちましたか?
🔗 関連するエラー
- Uncaught TypeError: Cannot read properties of undefined (reading 'length') — undefinedに対して.lengthを読んでいる
- Uncaught TypeError: Cannot set properties of null (setting 'textContent') — nullに対してプロパティを設定しようとしている
- Uncaught ReferenceError: Cannot access 'x' before initialization — let/constの宣言前にアクセスしている
- Uncaught TypeError: Assignment to constant variable. — constで宣言した変数に再代入しようとした
- Uncaught TypeError: x.forEach is not a function — forEachできない値に対してforEachしている
🔗 別カテゴリの関連エラー
📖 この問題を学べるレッスン
✏️ 手を動かして練習
📝 関連ブログ記事
- プログラミングのエラーメッセージの読み方 — エラーの読み方を基礎から解説
- JavaScriptとは?初心者向けにわかりやすく解説 — 変数・関数・イベントの基本
- JavaScriptでボタンクリックを動かす方法 — ボタンクリック時の動作を解説