I am dynamically generating a div and want to change its content via html()/text(), but its not working.
Here's the code:
var div = '<div class="ps_album"><img alt="" src="images/1px.gif" class="thmb"><div class="ps_desc"><h2>title</h2></div></div>';
$(div).find('.ps_desc').html('<h1>Hello</h1>');
$(div).appendTo('body');
in above code, the 3rd line i.e.
$(div).find('.ps_desc').html('<h1>Hello</h1>');
not working.. why??
The problem is that you're re-evaluating $(div)
. The first line that operates on the not-yet-added DOM fragment does not update the string value of "div". Thus, the second time you create $(div)
you start back over with the original fragment!
Try this:
$(div).find('.ps_desc').html('<h1>Hello World</h1>').end().appendTo($('body'));
The jQuery .end()
method "pops" the effect of the preceding .find()
call, so in this case it gets you back to the original point of navigation, which is the fragment you're building from the string. The subsequent call to .appendTo()
therefore will act on the outer <div>
you've built, and so that should do the right thing.
Try this:
$(div).appendTo('body');
$('body').find('.ps_desc').html('<h1>Hello</h1>');
$(div).appendTo('body');
$('.ps_desc').html('<h1>Hello</h1>');
UPDATE:
A working demo: http://jsfiddle.net/nbF2H/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With