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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

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?

Answers:

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

Questions:
Answers:

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.

Questions:
Answers:

Another way that worked best for me:

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

Questions:
Answers:

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

Questions:
Answers:

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

Questions:
Answers:

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

Questions:
Answers:

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.

Questions:
Answers:
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');

Questions:
Answers:

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

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

Questions:
Answers:

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

Questions:
Answers:

Can you add a container DIV around your “secondHeader” div? Then you’d use:

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

Questions:
Answers:

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.