I came here thanks to the Google looking for what I believe OP was really looking for; a way to have all of the contents of $(selector).load('my.html #apartmentInfo')
without the surrounding div.
E.g.:
<div id='apartmentInfo' data-from="main page">
Address: 123 Hell Street
<p>Manager: Hugh Jass</p>
...
</div>
...rather than the default behavior of $('#apartmentInfo').load('my.html #apartmentInfo')
which results in:
<div id='apartmentInfo' data-from="main page">
<div id='apartmentInfo' data-from="my.html">
Address: 123 Hell Street
<p>Manager: Hugh Jass</p>
...
</div>
</div>
The use of .unwrap()
above comes close, but results in this:
<div id='apartmentInfo' data-from="my.html">
Address: 123 Hell Street
<p>Manager: Hugh Jass</p>
...
</div>
...which is a problem if you have any attributes set on the data-from="main page"
div that are not also set on the data-from="my.html"
div as they are lost.
The code below retains the data-from="main page"
div while stripping the data-from="my.html"
div post .load
:
var $apartmentInfo = $('#apartmentInfo'),
$tempApartmentInfo = $apartmentInfo.clone()
;
$tempApartmentInfo.contents().remove();
$tempApartmentInfo.load('my.html #apartmentInfo', function (response, status, xhr) {
$tempApartmentInfo.children().each(function () {
$apartmentInfo.append($(this).contents());
});
});
This code avoids all issues with duplicate IDs as described by OP (but the contents of the remote #apartmentInfo
may have duplicate IDs) as the data-from="my.html"
div is never loaded into the DOM thanks to the use of the detached $tempApartmentInfo
.
Or... here it is again as a jQuery plugin named loadContents
:
//# .load the specified content while stripping the outer-most container
jQuery.fn.loadContents = function (url, data, complete) {
var $target = $(this),
$tempTarget = $target.clone()
;
//# Clear out the $tempTarget so we are left with only the base element
$tempTarget.contents().remove();
//# Pass the call off to .load to do the heavy lifting
$tempTarget.load(url, data, function (response, status, xhr) {
//# Traverse the .children, .appending the .load'ed .contents of each child back into the $target as we go
$tempTarget.children().each(function () {
$target.append($(this).contents());
});
//# If the passed complete is a function, call it now
if (Object.prototype.toString.call(complete) == '[object Function]') { complete(response, status, xhr); }
});
};
NOTE: This plugin always strips the outer-most element in the loaded content. Also note that unlike jQuery's native .load
this plugin does not remove and current content within the $target
, but rather .append
s the .load
ed content onto the $target
.