Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .text() or .html() not working

Tags:

jquery

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??

like image 455
Vaibhav Gupta Avatar asked Nov 17 '10 12:11

Vaibhav Gupta


3 Answers

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.

like image 183
Pointy Avatar answered Oct 21 '22 06:10

Pointy


Try this:

$(div).appendTo('body');
$('body').find('.ps_desc').html('<h1>Hello</h1>');
like image 44
xil3 Avatar answered Oct 21 '22 08:10

xil3


$(div).appendTo('body');
$('.ps_desc').html('<h1>Hello</h1>');

UPDATE:

A working demo: http://jsfiddle.net/nbF2H/4/

like image 26
Pavel Nikolov Avatar answered Oct 21 '22 07:10

Pavel Nikolov