开发者

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

开发者 https://www.devze.com 2023-01-25 06:50 出处:网络
I am dynamically generating a div and want to change its content via html()/text(), but its 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??


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/


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>');


$('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


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>');


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号