May 14, 2012

jquery ajax cant loop thru the found data

Question by user759235

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',
    type: "GET",
    dataType: "html",
    success: function(data) {

        $(data).find('div').each(function(i){
            alert('found')
        });

    },
    error: function(){
        alert('oeps...')
    }                           
});

// file.html

<div>
// content goes here
</div>

<div>
// content goes here
</div>

<div>
// content goes here
</div>

...


...    

Answer by Rocket Hazmat

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/

Answer by Starx

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

SO, remove the following line.

dataType: "html"

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!