tags:

views:

144

answers:

3

Hello,

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.

A: 

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

Yobi21
this seems backwards
cballou
Doesn't this replace the content of $("<div>World</div>") with the content of $("#Hello").html()? Cause that's not what I want at all.
Pickels
Sorry I misread they question. You are right.
Yobi21
+3  A: 

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());
cballou
Thanks, but I want it the other way around. I currently have the $("<div>World</div>") selected and not the element with the id Hello.
Pickels
+1  A: 

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