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 jus
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");
Another way that worked best for me:
$('#div_to_replace').load('/ajax/loader', function() {
$(this).children(':first').unwrap();
});
I had the same problem. My solution that worked for me was that I embedded a child div inside and updated the child div:
HTML:
<div id="secondHeader">
<div id="secondHeaderChild">
What currently is in secondHeader goes here....
</div>
</div>
Ajax:
$("#secondHeader").replaceWith($("#secondHeader").load("/logged-in-content.html
#secondHeaderChild"));
var target = '#secondHeader';
var pathname = '/logged-in-content.html';
var source = pathname + ' ' + target;
var temp = jQuery('<div></div>');
temp.load(source, function() {
jQuery(target).replaceWith(temp.contents());
});
or as function
$.fn.replaceWithRemote = function( source, callback ) {
var target = $(this);
var temp = $('<div></div>');
temp.load(source, function() {
target.replaceWith(temp.contents());
if (callback != null){
callback();
}
});
}
$('#secondHeader').replaceWithRemote('/logged-in-content.html #secondHeader');
$.load isn't really the best choice here since that function's intended to just fill in the contents of a div, as you've seen. You can just use $.get instead and set the callback function to replace your original div, or change logged-in-content.html to exclude the div.
Also be aware that as a Javascript-based solution, if your users look at the source, they'll see that they can get access to logged-in-content.html by just typing it in their address bar if you're not securing it somehow else.
Can you add a container DIV around your "secondHeader" div? Then you'd use:
$('#secondHeaderContainer').load('/logged-in-content.html #secondHeader');