user3708999 user3708999 - 1 year ago 57
jQuery Question

How to traverse dom tree from a list of elements

I have HTML snippet which looks like this. I generate this snippet multiple times form the backend. When I click the Save button, I catch which Save button was clicked using $(this) selector. Now I want to grab the attribute item-id of the corresponding Save button. I have the following jquery code snippet. But it does not work. I have tried to look but I don't know where the error is.

<td><input type="text" size="10" value="val1" item-id="id1"></td>
<td><input type="text" value="val2" size="4"></td>
<button class="btn btn-primary save-btn">Save</i></button>

Here is the jquery snippet

var ems = $(this).parent().siblings();
var item_id = ems[0].child().attr("item-id");

Answer Source

click doesn't work on dynamically added elements.You need to use on('click'). Also there is no method .child() so you need to use .children().first().

This is the corrected code:

$(document).on('click', '.save-btn', function(){
   var ems = $(this).parent().siblings();
   var item_id = ems.children().first().attr("item-id");

// The text
var text="";
text += "<td><input type=\"text\" size=\"10\" value=\"val1\" item-id=\"id1\"><\/td>";
text += "<td><input type=\"text\" value=\"val2\" size=\"4\"><\/td> ";
text += "<td>";
text += "  <button class=\"btn btn-primary save-btn\">Save<\/i><\/button>";
text += "<\/td>";

// Adding the text to html

$(document).on('click', '.save-btn', function(){
    var ems = $(this).parent().siblings();
    var item_id = ems.children().first().attr("item-id");
<script src=""></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download