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

3

7

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';
Joniejonina answered 31/3, 2014 at 13:2 Comment(2)
html("<div id='#friend_chooser_list'></div>"); your div id shouldnt include a #.. that should fix your problemSuspension
Gosh darn it... Yeah. that was it.THANKS!Joniejonina
B
7

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.

Bulletproof answered 31/3, 2014 at 13:8 Comment(1)
Someone answered this in the comments above already, but I'm marking this as the solution so anyone else who completely missed the obvious like I did can find the answer quickly.Joniejonina
A
3

When you dynamically add elements to the page, you have to refresh the event listeners.

You should group all your event listeners in a function :

function bindEvents(){
    $('*').off();

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

The first line (.off()) remove all the listener on the page (* = all the element, like in CSS).

Then just recall this function when you change the content of the page.

Have fun !

Apuleius answered 31/3, 2014 at 13:7 Comment(1)
Not when you are using $(document).on('click','[ID]', function(){}); that listener is appended to the document, not the element. The problem is with the selector he is using, see my answer.Bulletproof
U
0
$('.friend_chooser_pop #friend_chooser_list').html('something');

You can give it parent context and change $('.friend_chooser_pop').html("<div id='#friend_chooser_list'></div>"); to $('.friend_chooser_pop').html("<div id='friend_chooser_list'></div>");, in order to be visible in DOM for jQuery

Undue answered 31/3, 2014 at 13:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.