I have a UserControl. Ex:
<div id="divItem">
some html
</div>
The ajax request return new html of this UC from server. Ex:
<div id="divItem">
new html
</div>
I want to replace the old html by the new one. How could I do that. Thanks.
If you also return the div divItem
$("#divItem").replaceWith("NEW HTML");
Put the new HTML on the spot or replace the innerHTML, since they got the same container:
$("#divItem").html($("NEW HTML").html());
If you dont return the div divItem
Just put the new html:
$("#divItem").html("NEW HTML");
I guess replaceWith is what you search.
$('#divItem').replaceWith(serverResponse);
Placing data from AJAX calls into a DOM element can be done using .load()
.
$('#divItem').load('somePage.html');
If you want to replace 1 item with multiple items. You can try:
var item_1 = $('<div>').text('item 1');
var item_2 = $('<div>').text('item 2');
var item_3 = $('<div>').text('item 3');
// 1/.
// dont' use this way because it's hard to read
$('#divItem').prop('outerHTML', item_1.prop('outerHTML') + item_2.prop('outerHTML') + item_3.prop('outerHTML'));
// 2/.
// dont' use this way because it's same to the first's
$('#divItem')[0].outerHTML = item_1.prop('outerHTML') + item_2.prop('outerHTML') + item_3.prop('outerHTML');
// 3/.
// if you use this way, how can we continue replace "#divItem" with "item_2"?
var obj = $('#divItem').replaceWith(item_1);
// "replaceWith" returns an object which was replaced with "item_1"
// there is no way to continue with "item_2" and "item_3"
// sure, if you DON'T want to write a new line
item_1.after(item_2);
// or
item_2.insertAfter(item_1);
// 4/.
// if we write this, the result should be: "item 3item 2item 1"
$('#divItem').after(item_1).after(item_2).after(item_3);
// so, the correct **inline** solution should be:
$('#divItem').after(item_3).after(item_2).after(item_1).remove();
You just need
$('#divItem').html('new html');
This just replaces the div's innerHTML: http://api.jquery.com/html/
outerHTML
. The part you want to replace isinnerHTML