tuscan88
tuscan88

Reputation: 5839

Parse html from variable into jQuery object

I am doing an ajax post that returns some html and I want to find out how many divs with a class of entry there are in the returned html and then loop through them.

$.post(url, { 'data' : 'qdewde' }, function(data) {
    alert( $('entry', data).length );

    $('.entry', data).each(function() {
        // do something here
    });
}, 'html');

html returned:

<!DOCTYPE html>
<html lang="en">
<head>
<body>
    <div class="entry"><h1>Entry 1</h1></div>
    <div class="entry"><h1>Entry 2</h1></div>
    <div class="entry"><h1>Entry 3</h1></div>
</body>
</html>

The alert just outputs 0 though and I'm unable to loop through each .entry object. What am I doing wrong?

Upvotes: 0

Views: 49

Answers (1)

Jai
Jai

Reputation: 74738

For this you can create a virtual div to hold the response then only you can get the length:

$.post(url, { 'data' : 'qdewde' }, function(data) {
    var vd = $('<div>', {html:data});
    alert(vd.find('.entry').length);
}, 'html');

Upvotes: 1

Related Questions