Search code examples
javascriptjquerydom-traversal

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> 
<td>
  <button class="btn btn-primary save-btn">Save</i></button>
</td>

Here is the jquery snippet

 $(".save-btn").click(function(){
        var ems = $(this).parent().siblings();
       var item_id = ems[0].child().attr("item-id");
   }

Solution

  • 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
    $('body').html(text);
    
    
    $(document).on('click', '.save-btn', function(){
        var ems = $(this).parent().siblings();
        console.log(ems);
        var item_id = ems.children().first().attr("item-id");
        alert(item_id);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>