roozbubu
roozbubu

Reputation: 1176

jQuery each doesn't work with certain classes, or classes in general?

I'm using Phonegap to build a small (test only) Macrumors application, and remote hosts actually work (there is no same host browser restrictions). I am using the jQuery Load() function to load the contents of the Macrumors homepage http://www.macrumors.com/ into a bin, hidden div, then the each function to loop through all the article classes to show the title in a box with a link to the page.

The problem is, after the Macrumors HTML content is loaded, the each function doesn't work with the article class. Also, in the load function (which allows you to specify certain selectors, id's and classes included, to only load in those sections of the page) the class doesn't work; none of the classes do, in both the load function and each function. And many Id's don't work in the each function either.

Here is the code:

function onDeviceReady()
{
    // do your thing!
    $('#bin').load('http://www.macrumors.com/ #content');
    $('.article').each(function(){
    var title = $('a').html();
    $('#content').append('<b>'+title+'</b>')

    }); 
}

And the HTML stuff

    <body onload="onBodyLoad()">
       <div id="bin">
       </div>

       <div id="content">
       </div>

    </body>

I sincerely apologize if there's some very simple mistake here that I'm missing; I'm a major JS newbie.

Upvotes: 0

Views: 1041

Answers (1)

jfriend00
jfriend00

Reputation: 707786

.load() is asychronous. It hasn't completed yet when you're executing .each(). You need to put your .each() and any other code that wants to operate on the results of the .load() in the success handler for .load().

You would do that like this:

function onDeviceReady()
{
    // do your thing!
    $('#bin').load('http://www.macrumors.com/ #content', function() {
        $('.article').each(function(){
            var title = $('a').html();
            $('#content').append('<b>'+title+'</b>')
        }); 
    });
}

I'm also guessing that your .each() function isn't working quite right. If you want to get the link out of each .article object, you would need your code to be like this so that you're only finding the <a> tag in each .article object, not all <a> tags in the whole document:

function onDeviceReady()
{
    // do your thing!
    $('#bin').load('http://www.macrumors.com/ #content', function() {
        $('.article').each(function(){
            var title = $(this).find('a').html();
            $('#content').append('<b>'+title+'</b>')
        }); 
    });
}

Upvotes: 2

Related Questions