I cannot get the span id using jquery

Hi how can I get the id of my range using jquery. I tried some try but it doesn't work anything, it's the console input.

$(function () {

    for (var id = 0; i < data.length; i++) {
        var dynamicli = '<li class="">' +
            '<img src="path/to/image" class="_xy">' + data[i].name + '<i class="glyphicon glyphicon-user oncho"></i>' +
            '<span class="myspan" id="' + data[i].id + '></span></li>';
        $('#myullist').append(dynamicli);
    }

    $('#myullist').on('click', '.oncho', function () {
        var id = $(this).find('span').attr('id');
        console.log(id);
    });
});

      

//index.html

 <div class="wrapper-n">

    <ul id="myullist"></ul>
</div>

      

Edit . I change the click event to an oncho class so that when I click on the icon I can get the span id.

Edit: I tried to use find () but still I cannot get the undefined id

+3


source to share


1 answer


You missed the completion quote id

:

'<span class="myspan" id="'+data[i].id+'"></span></li>';
//                                      ^

      

UPDATE



Use next

as span

it is not a child .oncho

:

$('#myullist').on('click', '.oncho', function () {

    var id = $(this).next('span').attr('id');
    //               ^^^^^
    console.log(id);
});

      

+8


source







All Articles