1

Im trying to get all the messages from a facebook group post to display. with the code below:

   FB.api("/groupid/feed", function (response) {
    console.log(i + " : " + response.data.length);
    for (var i = 0; i < response.data.length; i++) {
        console.log(i + " : " + response.data[i].message);
        document.getElementById('posts').innerHTML = 'post: ' + i + ' : ' + response.data[i].message +'</br>';

    }

}) ;

I cant get the information in getElementId to show all the information that the console log shows. The console log shows 24 items and the website will just display 1 item. What do i need to change to get the information to display all 24 items not just the first one?

ekad
  • 14,436
  • 26
  • 44
  • 46
Brett
  • 161
  • 4
  • 16

2 Answers2

0

You are overwriting the innerHTML property in that for loop.

Instead, you should be appending it to the innerHTML.

Try this:

 FB.api("/groupid/feed", function (response) {
    for (var i = 0; i < response.data.length; i++) {
        console.log(i + " : " + response.data[i].message);
        document.getElementById('posts').innerHTML += 'post: ' + i + ' : ' + response.data[i].message +'</br>';
    }
 });

While you're at it, you can also refactor the loop entirely to use the native .forEach method.

It'll be cleaner, take a look:

 FB.api("/groupid/feed", function (response) {
    response.data.forEach(function(item, i){
      console.log(i + " : " + item.message);
      document.getElementById('posts').innerHTML += 'post: ' + i + ' : ' + item.message +'</br>';
    });
 });
Danny Delott
  • 6,756
  • 3
  • 33
  • 57
  • Thank you very Much! I was thinking i had to do with how the For statement was written but could not see how to fix it and google was not being much help this time – Brett Jun 08 '15 at 13:10
  • You're welcome! Please mark an answer as the solution if you're satisfied. – Danny Delott Jun 08 '15 at 14:42
0

Basically Dannys answer with some improvements. Never use innerHTML in a loop, and you can cache the length (although it will not be a big difference):

var feed;
FB.api("/groupid/feed", function (response) {
    for (var i = 0, count = response.data.length; i < count; i++) {
        console.log(i + " : " + response.data[i].message);
        feed += 'post: ' + i + ' : ' + response.data[i].message +'</br>';
    }
    document.getElementById('posts').innerHTML = feed;
});

You could also cache response.data, of course. And i would definitely use a for loop instead of forEach. forEach is only supported in IE9+ (not that i care about IE8 anymore, but still). for is also a lot faster than forEach: https://jsperf.com/for-vs-foreach/37

andyrandy
  • 72,880
  • 8
  • 113
  • 130