开发者

appendTo/prependTo but instead of adding I want to replace the content. htmlTo?

开发者 https://www.devze.com 2022-12-16 04:30 出处:网络
Quick jquery question: I know about appendTo and prependTo but is there maybe something like htmlTo? Yeah, I know it sounds silly but instead of adding elements like appendto and prependTo do I want

Quick jquery question:

I know about appendTo and prependTo but is there maybe something like htmlTo? Yeah, I know it sounds silly but instead of adding elements like appendto and prependTo do I want to replace the html.

$("<div>World</div>").htmlTo($("#Hello"))开发者_如何转开发;

So I want the div with World to replace all the content in the element with id Hello.

Edit: Thanks everybody for the answers but I think I wasn't clear. I am chaining a lot of functions onto one element and at the end I clone that element and I want to add it to an other div.

$("#World").hide().clone().htmlTo($("#Hello"));

Yes, I could just write it the other way around but I would like to only have 1 chain.


This should work as well:

$("<div>World</div>").appendTo($("#Hello").empty());


You can do it the other way around:

$('#Hello').html($('#World').html());

Or create a plugin that reverses the chain:

$.fn.htmlTo = function(elem) {
    return this.each(function() {
        $(elem).html($(this).html());
    });
}

$('#World').htmlTo('#Hello');


Based on your edit, if you do not care about moving the actual DIV container and merely it's contents you could easily do:

$('#Hello').html($('#World').hide().html());


How about:

$("<div>World</div>").appendTo($("#Hello").html(''));


$("<div>World</div>").html($("#Hello").html());

0

精彩评论

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

关注公众号