开发者

jQuery insert textarea value to div without affecting children elements

开发者 https://www.devze.com 2023-03-04 20:00 出处:网络
I\'m trying to insert the html value of textarea #ta inside div .yes without affecting or removing the children divs with class .no. Curren开发者_StackOverflowtly it\'s removing all content of of the

I'm trying to insert the html value of textarea #ta inside div .yes without affecting or removing the children divs with class .no. Curren开发者_StackOverflowtly it's removing all content of of the div including all children elements with class .no. Check jsfiddle at http://jsfiddle.net/f2rPz/.

<div class="yes">test
    <div class="no">no</div>
    <div class="no">no</div>
</div>
<textarea id="ta"></textarea>

$('#ta').keyup(function() {
    var x = $(this).val();
    $('.yes').html(x)
})


Check out my version which will replace the "test" text, but keep the .no divs.

Basically it boils down to: You want to keep a copy of the .no divs outside the DOM, then reattach them after replacing the content of .yes.

$('#ta').keyup(function() {
    var no = $('.yes > .no').remove();
    var x = $(this).val();
    $('.yes').html(x).append(no);
});

If you want to not affect all children, then replace the selector with '.yes > *' which will only select all the direct children.

http://jsfiddle.net/3PA6H/1/


Use the append function instead:

$('#ta').keyup(function() {
    var x = $(this).val();
    $('.yes').append(x)
})


Replacing html() with append() will do this.

Update: Here is the jsFiddle fork showing the result: http://jsfiddle.net/X7YQU/

0

精彩评论

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