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

Jquery

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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"));

Solution 3 - Jquery

Another way that worked best for me:

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

Solution 4 - Jquery

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");

Solution 5 - Jquery

Using $.get() worked for me but I had to extract the container from the response document first:

$.get("/page.html", function (data) {
    var elem = $(data).find('#container');
    $("#puthere").replaceWith(elem);
});

Solution 6 - Jquery

I always have a jQuery function defined like this:

	jQuery.fn.loadOuter = function( url, callback )
	{
		var toLoad = $(this);
		$.get(url, function( data ) {
			toLoad.replaceWith( data );
			if (callback != null && callback != undefined)
				callback();
		});
	}

Then I can either say

$(...).load(url)

or

$(...).loadOuter(url)

The second one does what you want to do. I also have a function called loadInner which just calls load for what its worth.

Solution 7 - Jquery

$.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.

Solution 8 - Jquery

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

Solution 9 - Jquery

After you have loaded the content, find its children #second and unwrap it.

$("#secondHeader").children().unwrap();

Solution 10 - Jquery

You want to wrap in div before inserting it.

$.ajax({
	url: "/logged-in-content.html",
	success: function(response){
	   	var loadedheader = $("<div/>").append(
	   	response.replace(/<script(.|\s)*?\/script>/g, "")
	   	).find('#secondHeader > *').html();
	   	$("#secondHeader").append(loadedheader);
	}
});

Solution 11 - Jquery

Can you add a container DIV around your "secondHeader" div? Then you'd use:

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

Solution 12 - Jquery

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"));

Solution 13 - Jquery

I had this issue as well, but I was able to use .load by restructuring the code like so: (jade)

div#view
   div.content
      block content

and the script like so...

$("#view").load( $(this).attr("href") + " div.content" )

so target the child instead of the same tag.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvipergtsrzView Question on Stackoverflow
Solution 1 - JqueryFunkaView Answer on Stackoverflow
Solution 2 - JqueryAli SarchamiView Answer on Stackoverflow
Solution 3 - JqueryTom RoseView Answer on Stackoverflow
Solution 4 - JqueryVictor 'Chris' CabralView Answer on Stackoverflow
Solution 5 - JqueryDavidWainwrightView Answer on Stackoverflow
Solution 6 - JqueryLeander ConradieView Answer on Stackoverflow
Solution 7 - JqueryRandyView Answer on Stackoverflow
Solution 8 - Jquerykey_View Answer on Stackoverflow
Solution 9 - JqueryPedro GóesView Answer on Stackoverflow
Solution 10 - JqueryJourkeyView Answer on Stackoverflow
Solution 11 - JquerydanblakerView Answer on Stackoverflow
Solution 12 - JquerymoriturusView Answer on Stackoverflow
Solution 13 - JqueryTimmerzView Answer on Stackoverflow