ラボ > Javascript関連:DOM関連、イベント関連
js, jquery イベント内での要素の取得
思うトコがあって…jqueryでのイベント発生時の対応にjavascriptで要素を取得したい
作成日:2023-09-26, 更新日:2023-09-26
jqueryでイベント設定
$(document).on('click','.tmp-box .tmp2-box button', function(e) { const formElement = $(this).parents(.tmp2-box).find('form'); // jqueryで要素取得 // const formElement = e.currentTarget.closest('.tmp2-box form'); // javascriptで要素取得 });
※「closest()」は「parents()」と似たような感じ。直近の親か、すべてか…の違い
javascriptでイベント設定
document.querySelector('.tmp-box .tmp2-box button').addEventListener('click', function() { // const formElement = $(this).closest('.tmp2-box').find('form'); // jqueryで要素取得 const formElement = this.closest('.tmp2-box').querySelector('form'); // javascriptで要素取得 });
FormData()にセットしたい
$(document).on('click','.tmp-box .tmp2-box button', function(e) { const formData_js = new FormData(e.currentTarget.closest('.tmp2-box form')); // JS const formData_jq = new FormData($(this).closest('.tmp2-box').find('form').get(0)); // Jquery });
エラーになった例
▼「.get(0)」が無いとエラー
$(document).on('click','.tmp-box .tmp2-box button', function(e) { const formData_jq = new FormData($(this).closest('.tmp2-box').find('form')); });
▼エラー内容
Uncaught TypeError: Failed to construct 'formData_jq': parameter 1 is not of type 'HTMLFormElement'.