tags:

views:

51

answers:

3

I'm pulling in a google news feed, then trying to take out some mal-formatting by accessing the newly-created DOM elements.

var aryClassElements = document.getElementById('google-news').getElementsByTagName('div');
alert("Found "+aryClassElements.length+" divs in Google News");

But this alert shows 0. It hasn't found the newly-created DOM elements. Ack!

If I add an extraneous alert ("hello world") in between loading the google news feed and asking the dom for div elements in google-news, it finds 20 div elements. I assume the user response time to click "OK" lets the DOM update.

Is there some plain javascript (not jquery) that will accomplish the same result?

Tx!

A: 

use setTimeout to create a artificial delay. The better way of doing it will be if you are using ajax to load the contents, on ajax complete, you set the new html and then try to find the DOM elements.

Teja Kantamneni
I am using Ajax to load the contents, using google's jsapi library. The code loads a feed url (in this case, http://news.google.com/news/search?aq=f -- where infodiv is my <div id="google-news"> and div is the new element constructed from the feed. This appendChild call has happened BEFORE I try to access the children of <div id="google-news", hence my confusion...
Summer
+1  A: 

If google-news provides callback hooks or pseudo events that you can attach functions to then use that. Most javascript API's have them these days. So my first recommendation is to read the documentation for it.

If not, then you can poll with setTimeout, say once per second, and execute your function when found:

function pollDOM () {
    var aryClassElements =
            document.
                getElementById('google-news').
                getElementsByTagName('div');

    if (aryClassElements.length) {
       // do stuff here;
    }
    else {
        setTimeout(pollDOM,1000);
    }
}
pollDOM();
slebetman
The odd thing is, I think I AM using the google news callback hook... ah, maybe not... thanks for pointing me in the right direction, I think I'll be able to get there from here. Gracias all!
Summer
A: 

To load the feed, I was using:

feed = new google.feeds.Feed(url);
feed.load(function(result) { [the function to add DOM elements here] }
[the function to read DOM elements here]

I just needed to restructure a little:

feed = new google.feeds.Feed(url);
feed.load(function(result) { 
  [the function to add DOM elements here]
  [the function to read DOM elements here]
}

And all is well! Rookie mistake, thanks you guys for pointing me in the right direction.

Summer