JQuery replace entire DIV using .load()
Asked Answered
T

3

8

I want to refresh a <div> on the close of a jQuery UI Modal Dialog.

My code is:

var dialog = jQuery('#divPopup').dialog({
    autoOpen: false,
    height: 450,
    width: 650,
    modal: true,
    open: function(event, ui) {
        jQuery('body').css('overflow', 'hidden');
    },
    close: function(event, ui) {
        jQuery('#divPopup').dialog('destroy').remove();
        jQuery("#bodyId").load("http://www.xyz.com/ #bodyId");
    }
});

But instead of replacing it, that adds the new <div> inside the old <div>:

<div id="bodyId">
    <div id="bodyId">
        New Response
    </div>
</div>

I want to replace old div bodyId with new div bodyId.

Tabby answered 16/1, 2012 at 5:55 Comment(2)
Are you sure your server dide script "http://www.xyz.com/#bodyId" does not include a <div id="bodyId"> in its output?Counterweigh
@Counterweigh there is a space before #bodyId. Have a look at .load() docs, chapter "Loading Page Fragments".Vaclava
V
12

Try to replace this:

jQuery("#bodyId").load("http://www.xyz.com/ #bodyId");

... with this:

jQuery("#bodyId").load("http://www.xyz.com/ #bodyId > *");

This works because you can use any selector after the URL. By using #bodyId > * instead of just #bodyId, you match everything that is inside the div, instead of the div itself.

You need this because .load() will not replace an element; it will append the result of the AJAX call to the element.

Alternatively, you could use .get() to load the data and manually perform the selection, like so:

$.get('http://www.xyz.com/', function(data) {
    var newContent = $(data).find('#bodyId').children();
    $('#bodyId').empty().append(newContent);
});

Examples of both methods are online here: http://jsfiddle.net/PPvG/47qz3/

Vaclava answered 16/1, 2012 at 6:3 Comment(0)
S
0

You could also use jquery.get.

$.get('http://www.xyz.com/', function(data) {
  $('#bodyId').html(data);
});
Shoemaker answered 16/1, 2012 at 6:10 Comment(0)
J
-4

you may be use this code like

$('#bodyID').remove();
$('#bodyID').load();
Janenejanenna answered 16/1, 2012 at 6:0 Comment(1)
I don't think this would work. The first line would remove the div from the DOM tree, which means the jQuery selection on the second line won't have a match.Vaclava

© 2022 - 2024 — McMap. All rights reserved.