Angie
Angie

Reputation: 521

jQuery.ajax filter doesn't work on few selectors

I'm using wordpress (4.1) and jQuery 1.11 - I want to load other page content in page I'm right now - using ajax. I can append whole html (width head, meta and all that stuff), I can filter images or spans, but when I'm trying to filter section or #content there is empty response. There are no errors in Console.

jQuery:

$('nav a').click(function(load) {
    load.preventDefault();
    jQuery.ajax({
        type: "GET",
        url: jQuery(this).attr('href'),
        dataType: "html",
        success: function(out) {
            result = jQuery(out).find('section');
            jQuery('#change').append(result);
        }
    });
});

HTML looks like this:

<section id="content">
 ....
</section>

I think I tried everything. With "img" instead of section there is content (part of it is from section#content, so it's weird).

Anyone know what can be wrong? I'm using this same code in another wordpress with this same version, and all works like a charm. I don't have any more jQuery libraries loaded.

Upvotes: 0

Views: 86

Answers (1)

000
000

Reputation: 27247

If your full html response is:

<section id="content">
 ....
</section>

then the issue is that $.find will only find the descendants of an element, and it will not find the top-level element itself. As an example:

$('<p><a>hi</a></p>').find('p') // => []
$('<p><a>hi</a></p>').find('a') // => [{a element}]

A quick workaround is:

$('<div></div>').append($('<p><a>hi</a></p>')).find('p') // => [{p element}]

Upvotes: 1

Related Questions