Pa3k.m
Pa3k.m

Reputation: 1166

.load() contents of a div instead of the whole div

$('#content').load(href + ' #content');

is it possible to load only the contents of #content instead of loading the whole <div id="contents"> so I can prevent having <div id="contents"><div id="contents"></div></div>?

I forgot to place wrappers on a lot of pages and it would save me some time if there's a workaround on this.

Upvotes: 0

Views: 68

Answers (4)

matt
matt

Reputation: 91

The $.load function takes handler for when the request is complete (http://api.jquery.com/load/). So when you request the matched '#content' element from the other page, have the complete function only return the inner html. Something like:

$('#content').load(href + ' #content',function(data){ return data.html(); });

Upvotes: 0

Awena
Awena

Reputation: 1022

The load() method is mostly used to load remote data..

You cannot have two elements with the same ID..

$( "#result" ).load( "page.html #desiredContent" );

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388396

I think you can try

$('#content').load(href + ' #content > *');

Note: If #content has any text nodes as its children(not descendants) then it may not work(the text nodes may not get copied)

Demo: Fiddle


Another solution is to manually remove the second wrapper, if it exists like

$('#content').load('ajax.html' + ' #content', function () {
    if ($(this).children('#content').length) {
        $(this).contents().unwrap()
    }
});

Demo: Fiddle

Upvotes: 1

Paul S.
Paul S.

Reputation: 66364

Why not stick them somewhere else first then move over what you want

$(document.createElement('div')).load(href + ' #content', function (e) {
    var elms = this.firstChild.childNodes,
        parent = document.getElementById('content');
    while (elms.length) {
        parent.appendChild(elms[0]);
    }
});

Upvotes: 0

Related Questions