How to change HTML content of dynamically generated element in jQuery

I have long understood that for dynamically added content, adding listeners and events, such as click and focus, should be done using $(document).on('click','[ID]', function(){}); .... etc.

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

For example, I use this code to add an element:

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

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

 $('#friend_chooser_list').html('something'); document.getElementById('friend_chooser_list').innerHTML = 'something'; 
+6
source share
3 answers

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

It will work.

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

If you intend to include # in the identifier and want it to work, you can use it like this:

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

This eludes # and allows jQuery to get the correct element anyway. I would not recommend this, it can get confused pretty quickly.

+5
source

When you dynamically add elements to a page, you need to update the event listeners.

You should group all event listeners into functions:

 function bindEvents(){ $('*').off(); $('a.fonction').click(function(){ /* ... */ } } 

The first line (.off ()) deletes the entire listener on the page (* = the entire element, as in CSS).

Then just remember this function when changing the contents of the page.

Good luck

+3
source
 $('.friend_chooser_pop #friend_chooser_list').html('something'); 

You can specify its parent context and change $('.friend_chooser_pop').html("<div id='#friend_chooser_list'></div>"); on $('.friend_chooser_pop').html("<div id='friend_chooser_list'></div>"); to be visible in the DOM for jQuery

0
source

All Articles