How can I use jQuery.load to replace a div including the div

I have a div with the id of "secondHeader" and I want to replace that entire div with another div with the same id of "secondHeader" but instead of replacing it , it just adds the loaded div inside the first one.

$("#secondHeader").load("/logged-in-content.html #secondHeader");

This is what happens...

<div id="secondHeader"><div id="secondHeader"></div></div>

What I want to happen is the secondHeader div from the ajax load to totally replace the secondHeader in the initial page.

I know it sounds dumb, but here's what I'm trying to accomplish...When a user is not logged in, they see a non-logged in header. I am using ajax to allow the person to log into the site and I want to replace the non-logged in header with the logged in one via ajax.

I have tried everything I know such as...

$("#secondHeader").replaceWith($("#secondHeader").load("/logged-in-content.html #secondHeader"));

...and using .remove() before hand...

Any ideas?


Could you refine your selector in the load() method?

For example,

$("#secondHeader").load("/logged-in-content.html #secondHeader > *");

This way, you're not grabbing the div itself, you're grabbing its contents.


I think the best way is to use get instead of load. In your case you can do like this:

$.get("/logged-in-content.html #secondHeader", function(data) {
     $("#secondHeader").replaceWith(data);
});

[Edit: removed a paren]

Update: If /logged-in-content.html has more than just the code you need, you can wrap the returning data in another jQuery object and use .find() to extract the container. Try this:

$("#secondHeader").replaceWith($(data).find("#secondHeader"));


Another way that worked best for me:

$('#div_to_replace').load('/ajax/loader', function() {
    $(this).children(':first').unwrap();
});

Final Answer:

$.fn.loadWith = function(u){var c=$(this);$.get(u,function(d){c.replaceWith(d);});};
$("#test").loadWith("somelink.html");

jQuery load adds the response INTO the element selected. jQuery's replaceWith REPLACES the selected element.

<div id="curElement">start</div>

$("#curElement").load("somelink.html");
will result in:
<div id="curElement">What ever was in somelink.html</div>


$("#curElement").replaceWith("somelink.html");
will result in:
What ever was in somelink.html

I suggest adding a function to jQuery that does both:

$.fn.loadWith = function(u){
    var c=$(this);
    $.get(u,function(d){
        c.replaceWith(d);
    });
};
$("#test").loadWith("somelink.html");