Search code examples
javascriptjqueryhtmlnested-sortable

Get clicked li id


I have the following list:

<ol class="sortable ui-sortable">
    <li id="list_1608"><div>One</div></li>
    <li id="list_1609"><div>Two</div></li>
    <li id="list_1610"><div>Three</div></li>
</ol>

I want to get the id of any li that is clicked. I have tried the following code but get no alert.

$("li").click(function() {
    var myid = $(this).attr("id");
    alert(myid);
});

I am using this in conjunction with the nestedSortable jQuery Plugin.

Where am I going wrong?

Ok Further info, the list items are added after the dom is loaded.

If the items are loaded to start with it does work, apologies.


Solution

  • Your code is working here, you may need to put it in document.ready() or need to add jQuery files. Using this.id instead of $(this).attr("id") is better option here as it is javascript and gives you performance benefit.

    $(document).ready(function(){
    
         $("li").click(function() {
            //var myid = $(this).attr("id");
            alert(this.id);
         });
    
    })