How do I change the HTML content of a dynamically generated element in Jquery

not_a_generic_user picture not_a_generic_user · Mar 31, 2014 · Viewed 12.1k times · Source

I long ago learned that for dynamically added content, attaching listeners and events like click and focus must be done by using $(document).on('click','[ID]', function(){});.... etc.

However, what I'm trying to do is change the HTML value of a specific element that has been dynamically added.

For instance, I use this code to add the element:

$('.friend_chooser_pop').html("<div id='#friend_chooser_list'></div>"); 

Now how do I access #friend_chooser_list and set its HTML value? Neither one of these works:

$('#friend_chooser_list').html('something');
document.getElementById('friend_chooser_list').innerHTML = 'something';

Answer

Allan Kimmer Jensen picture Allan Kimmer Jensen · Mar 31, 2014

This should work, your problem is that you included a # in your id, this is not needed here.

This would work.

$('.friend_chooser_pop').html("<div id='friend_chooser_list'></div>");
$('#friend_chooser_list').html('something');

If this is your intend to include # in the ID and you want it to work you can use it like this:

$("#\\#friend_chooser_list").html('something');

It's escaping the # and allowing jQuery to get the right element anyway. I would not recommend this, it can get confusing pretty fast.