Mosayeb Mosayeb - 2 months ago 17
jQuery Question

JQuery: Access Dynamic Element after append

I have a problem with accessing the Elements that appended in my website.
this is my code:

socket.on('userupdate', function (data) {
var userslist = [];
$('#users-list').html('');
data.forEach(function (item) {
userslist.push("<a><li id='chat-private' username=" + item.username + " userid=" + item.userid + ">" + item.username + "</li></a>");
});
$('#users-list').append(userslist);
});
$("#chat-private").click(function () {
alert("We have Access!");
});


but nothing happened. thank you.

Answer

Firstly, you want the give the chat-private elements a class, otherwise you will have duplicate id attributes, which is invalid.

Secondly, you need to use a delegated event handler because those elements are not present in the DOM on page load. Try this:

socket.on('userupdate', function (data) {
    var userslist = [];
    data.forEach(function (item) {
        userslist.push("<li class='chat-private' username=" + item.username + " userid=" + item.userid + "><a>" + item.username + "</a></li>");
    });
    $('#users-list').html('').append(userslist);
});
$('#users-list').on('click', '.chat-private', function () {
    alert("We have Access!");
});

Note also that the a element should be inside the li, otherwise the HTML will be invalid and you may get rendering errors.

Comments