Vaibhav Gupta
Vaibhav Gupta

Reputation: 1612

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

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

Upvotes: 9

Views: 48822

Answers (7)

live-love
live-love

Reputation: 52366

Make sure you are accessing the correct id.

If you are using ASP.NET, it could be because ASP.NET changes the id names, if you add "runat="server".

Try accessing it by using the class name instead and see if it works.

    <td id="mytd" class="myclass" runat="server"></td>
    $('.myclass').html()
    $('.myclass').text()

Upvotes: 0

vad
vad

Reputation: 1

Today I am presenting on improvements to security note templates

This is an example of XSS vulnerability :

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

Upvotes: 0

tbleckert
tbleckert

Reputation: 3803

$('body').append('<div class="ps_album"><img alt="" src="images/1px.gif" class="thmb"><div class="ps_desc"><h2>title</h2></div></div>')
         .find('.ps_desc')
         .html('<h1>Hello World</h1>');

See here

Upvotes: 0

Pointy
Pointy

Reputation: 413702

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.

Upvotes: 15

Pavel Nikolov
Pavel Nikolov

Reputation: 9541

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

UPDATE:

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

Upvotes: 1

xil3
xil3

Reputation: 16439

Try this:

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

Upvotes: 1

Chinmayee G
Chinmayee G

Reputation: 8117

You should reverse the order i.e.

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

find and html methods works on elements inside DOM. Unless you append your HTML string to DOM these jquery methods will not work.

Option II

var div = $('<div class="ps_album"><img alt="" src="images/1px.gif" class="thmb"><div class="ps_desc"><h2>title</h2></div></div>');

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

Upvotes: 0

Related Questions