0
0

th:ifを使った時のaddEventListener

Posted at

結論

qiita.js
const 目的のボタン等;
if(目的のボタン等){
    目的のボタン等.addEventListener
}

経緯

th:ifを使って表示の切り替えを行うボタンにクリックイベントを追加しようとしたら

sample.html
<div th:if="${boolean}">
    <button id="sample-btn">OK<button>
</div>
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

と表示されてボタンが想定通りに作動しない。

解決方法

どうやらth:ifで非表示にしているオブジェクトは、ないものとしてふるまってしまいjavascriptを読み込む際にイベントを追加しようとしているオブジェクトが見つからなくなってしまうようだ。

そのため、そのオブジェクトが存在するかどうかをif()で判断し、それが存在するときのみイベントを追加するようにすればよいらしい。

sample.js
const samplebtn = document.getElementById(sample-btn);
if(samplebtn){
    samplebtn.addEventListener
}

th:ifの説明

th:if="boolean"
thymeleafで追加されるHTMLの拡張
booleanに入る変数によってオブジェクトを存在させるかどうかを判断できる。

0
0
0

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