LoginSignup
5
3

More than 3 years have passed since last update.

後から(動的に)追加された要素に対してイベントを設定する

Posted at

Jsを用いて、後から(動的に)追加されたHTML要素に対してイベントを設定するためには、以下のような通常通りの方法を用いても動作させることはできない。なぜなら、動作させたいHTML要素は、もともと存在していたものではないからである。もし、もともと存在していたものであれば、通常通りの方法を用いて動作させることができる。


$(セレクタ).on('click', function(){ 処理 })

では、どうやってイベントの設定を行うのかというと。documentを用いて実装すればできる。documentとは、、Webページを構成しているHTML要素をすべて取得する便利なオブジェクトのことである。


$(document).on("click",".user-search-add.chat-group-user__btn.chat-group-user__btn--add",function(){
 console.log(document)

以下の動画では、documentの中には、Webページを構成しているHTML要素が取得されていることがわかる。
https://gyazo.com/8f8f4a4b9c9b1f887609ca5a8a0e07e4
https://gyazo.com/234ebc303cd8f50645c0076f75b81442
https://gyazo.com/2d23fa09614613d42bf3b98d3d62c3a1

<参考記事>
https://qiita.com/negi/items/6ec0d3cedba499eac81a
https://www.sejuku.net/blog/30970#document

5
3
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
5
3