Skip to content Skip to sidebar Skip to footer

Jquery Ajax Cant Loop Thru The Found Data

I want to loop thru a file which is loaded with ajax, but it won't loop, i have tried a couple of things but I cant get it to work. // jquery $.ajax({ url: 'file.html', typ

Solution 1:

You need to change .find to .filter. This is because .find searches the children descendants of all the elements, but since your html file is just <div>s, you need to use .filter to find them.

DEMO: http://jsfiddle.net/zuPVp/

Solution 2:

You dont need to specify html as the datatype, it is not needed.

SO, remove the following line.

dataType:"html"

Solution 3:

The reason that doesn't work is because .find looks for descendants in data, all of those divs are at the root.

You can create an empty div then set the html of that div to your data. This will ensure find works as the divs will then be descendants.

$.ajax({
    url: 'file.html',
    type: "GET"success: function(data) {
        $('<div/>').html(data).each(function(index, item) {
            console.log(item);
        });
    },
    error: function(){
        console.log('error')
    }                           
});

Or you could use filter.

$.ajax({
        url: 'file.html',
        type: "GET"success: function(data) {
            $(data).filter('div').each(function(index, item) {
                console.log(item);
            });
        },
        error: function(){
            console.log('error')
        }                           
    });

Solution 4:

It's hard to know what you are trying to do, but I'm guessing it's this:

$.ajax({
    url: 'file.html',
    type: "GET"success: function(data) {
        $.each($('div', data.outerHTML), function(index, item) {
            console.log(item);
        });
    },
    error: function(){
        console.log('error')
    }                           
});

Solution 5:

In this case, .find() does not work because the HTML you are searching does not contain any div children nodes. To fix this, first append the items to some container and then use .find().

http://jsfiddle.net/jbabey/hvkw9/1/

var html = $('<div>first div</div><br /><div>second div</div>');

// 0, no child divs in htmlconsole.log(html.find('div').length);
// 2, now the divs in html are children of an intermediate divconsole.log($('<div>').append(html).find('div').length);

Post a Comment for "Jquery Ajax Cant Loop Thru The Found Data"