0

I have some list tag in my HTML page .I want to find the text and id of list tag separately. Since my list is created in the run time so I cant figure out how to get the id and text value.

I have tried this

$("#users li").click(function(e) 
{ 
     console.log($(this).text());
     console.log($(this).id);
});

But it is not triggering any click event.

HTML part

<div class="card card-body bg-light">
    <h3>Online Users</h3>
    <ul class="list-group" id="users"></ul>
</div>

jquery part

$(function () {
    var socket =io.connect();
    var $users =$('#users');

    socket.on('get users',function(data){
    var html='';
    for(var i=0;i<data.length;i++){
         html+='<li class="list-group-item" id="'+i+'">'+data[i]+'</li>';
    }
    $users.html(html);
    });

    $($users).click(function(e) 
   { 
    console.log($(this).text());
    console.log($(this).id);
   });
}
Dipto Roy
  • 163
  • 1
  • 14

3 Answers3

2

Maybe try $users.on("click",".list-group-item",function(...){ .... });

Edit:

$users.on("click",".list-group-item",function(e){ console.log($(this).text()); console.log(e.target.id); });

@Dipto Roy

Dipto Roy
  • 163
  • 1
  • 14
0

Try with this code

$(document).on('click','#users li',function(){
    console.log($(this).text());
    console.log($(this).attr('id'));
});
Kirtee
  • 141
  • 9
  • 1
    Actually since `$('#users')` is likely static, it is closer to the event target to do `$('#users').on('click','li',function(){` or `$users.on('click','li',function(){` – mplungjan Jul 15 '19 at 05:07
  • I have tried this. I can print the text of list tag. But the printing of id is giving undefined. – Dipto Roy Jul 15 '19 at 05:23
  • try with consoel.log($(this).attr('id')); check my edited answer – Kirtee Jul 15 '19 at 06:26
0

you can try this,

   $("#users li").click(function(e) 
   { 
    console.log($(this).text());
    console.log(this.id);
   });
ArunKumar M N
  • 1,256
  • 1
  • 10
  • 22