Yax
Yax

Reputation: 2189

Both jQuery filter() and find() Returns Error on AJAX Reponse

My AJAX returns either a HTML all wrapped in <div class = 'Post'>....</div> or just No new data yet.

var request = $.ajax({
  url: "/mysite/load_latest/",
  type: "POST",
  data: { user_id : userID },
  dataType: "html"
});
request.done(function( msg ){   
    console.log(msg);
    var class1 = $(msg).filter(".Post");
    console.log(class1);            
});

I want to check if .Post exist in the returned HTML but it returns this error: Uncaught Error: Syntax error, unrecognized expression: <div class = 'Post'>...content...</div>

I tried $(msg).find(".Post"); but it returns the same error.

Upvotes: 0

Views: 59

Answers (2)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

for example in html

<div class="msg_html"></div>

in your code

request.done(function( msg ){   
    $('.msg_html').html(msg);
    $('.Post').css('background','yellow');
    alert('Now your Post class has a background yellow if its a content in it');         
});

Upvotes: 0

dashtinejad
dashtinejad

Reputation: 6253

Try to make a new element, append your response to it, then search for desired element:

request.done(function( msg ) {
    var element =
        // make a new element on the fly
        $('<div></div>')

        // put the `msg` response inside it
        .html(msg)

        // now search for `.Post` element
        .find('.Post')
    ;

    // the length will be `0` or more
    alert(element.length);
});

Upvotes: 1

Related Questions