Skip to content Skip to sidebar Skip to footer

Jquery Ajax $.get Result Doesn't Find Class

I got stuck on a seemingly simple problem. I want to fetch the resulting HTML from a ajax request and look whether or not a specific element has a specific class and take the HTML

Solution 1:

I would first echo out the response and make sure your getting the correct html back.

Then you can confirm you have the html with the specific class.

The .hasClass is exactly what you want, the undefined is probably because you're not getting the html back, to confirm console log it.

use $('Your Div').contents();

To get the html content

Then $('Where you want to place html Div').append(Your Div);


Solution 2:

It looks like, you are trying to get a property which should not exist i.e

$url.url 

You $.get code block should look like this

   $.get($url, function(response) {
                var $response = $(response);

                var $body = $response.find('.js-wrapper').html();
                var _isLight = $response.find('.js-wrapper').hasClass('body-light');

                console.log($body);
                console.log(_isLight);

                History.pushState({ state:$url }, $title, $url);
        });

Solution 3:

Seems to work in the

{ http://jsfiddle.net/Px6tu/ }

Please try to console log the response to make sure you are getting what is expected.

Also have a look Ajax Response Finding HTML Fragments Using Find


Solution 4:

Thanks to @Girish Sakhare comment and @Alexanders answer here I got the solution:

var $response = $("<div/>").html(response);

So the function looks like this now:

$(function() {
    $('.js-nav').on('click', function(e) {
        e.preventDefault();
        var $this = $(this);
        var $url = $this.attr('href');

        $.get($url, function(response) {
                var $response = $("<div/>").html(response);

                var $body = $response.find('.js-wrapper').html();
                var _isLight = $response.find('.js-wrapper').hasClass('body-light');

                console.log($body);
                console.log(_isLight);

                History.pushState({ state:$url }, $title, $url);
        });
    });
});

So I had to append the response to an empty div first.

Thanks


Post a Comment for "Jquery Ajax $.get Result Doesn't Find Class"