LoginSignup
2
1

More than 3 years have passed since last update.

jQueryで動的に生成されたHTML要素から属性値を取得する方法

Posted at

動的に生成されたHTML要素から属性値を取得する方法

attrメソッドを使えば、要素が持つ属性の値を取得することができる(始めから設定してあるHTML要素にも使える。)。

動的に生成されたHTML要素の部分

       var html = `<div class="comment">
                      <p data-p-comment-id="${comment.id}">
                        <strong>
                          <a href=/users/${comment.user_id}>${comment.user_name}</a>
                          :
                        </strong>
                        ${comment.text}
                        <a href=/tweets/${comment.tweet_id}/comments/${comment.id}/edit class="ajax_edit_button" >編集</a>
                        <span class="ajax_delete_button" data-tweet-id="${comment.tweet_id}" data-comment-id="${comment.id}" method="delete" >削除</span>
                      </p>
                    </div>`
        return html;

ここから、data-tweet-idというid属性(下から4行目の部分)を取得する方法
イベント発火したthisにattrメソッドを適用して、id属性を取得する。

$(document).on("click",".ajax_delete_button",function(){
        var get_tweet_id = $(this).attr('id');
2
1
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
2
1