how to get the data-id of the li on span class click

I have data showing using ul li as below.

<ul class="quotes">
    <% for(var i=0; i<quotes.length; i++) {%>
        <li class="quote" data-id= "<%= quotes[i]._id %>">
            <span><%= quotes[i].name %></span> - 
            <span><b><%= quotes[i].price %></b></span>
            <span class="remove">X</span>
        </li>
    <% } %>
</ul>

When I click on span with class remove i want to get the data-id of that li.

I have tried,

$('.remove').on('click',  function(e){
    $(this).attr('data-id');
});

and also tried $(this).closest(li).. But I am not getting it.

2 answers

  • answered 2018-07-11 04:27 31piy

    You could search the parents and get the data-id of it:

    $('.remove').on('click', function() {
        $(this).parents('li').attr('data-id');
    });
    

    Or, simply get the immediate parent, and use the data method to get the value:

    $('.remove').on('click', function() {
        $(this).parent().data('id');
    });
    

  • answered 2018-07-11 04:28 Kiran Shahi

    You can use either $(this).parent().attr('data-id') or $(this).closest('li').attr('data-id') or $(this).parents('li').attr('data-id');

    closest() selects the first element that matches the selector, up from the DOM tree.

    parent() selects one element up the DOM tree.

    parents() method is similar to parent() but selects all the matching elements up the DOM tree.

    $('.remove').on('click',  function(e){
        console.log($(this).parent().attr('data-id'));
        console.log($(this).closest('li').attr('data-id'));
        console.log($(this).parents('li').attr('data-id'));
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul class="quotes">
            <li class="quote" data-id="1">
                <span>name</span> - 
                <span><b>123</b></span>
                <span class="remove">X</span>
            </li>
            <li class="quote" data-id="2">
                <span>name</span> - 
                <span><b>123</b></span>
                <span class="remove">X</span>
            </li>
            <li class="quote" data-id="3">
                <span>name</span> - 
                <span><b>123</b></span>
                <span class="remove">X</span>
            </li>
    </ul>