Having trouble with AJAX and innerHTML

Hi, I’m trying to learn AJAX, so I used https://jsonplaceholder.typicode.com to create a program that fetches data and displays it, I also added a button that displays comments for each post, and the code works for the first few posts, for the later posts (30 onwards), I get the following error:

Uncaught TypeError: Cannot set property ‘innerHTML’ of undefined

now sometimes, I don’t know how, but the code will work for later posts, but sometimes it doesn’t, it’s quite confusing, I’ve used console.log to see if the comments are retrieved, and they are always logged into the console on clicking the button, for some, it’s just not inserted in DOM . I’d appreciate any help in this, thanks!

Here’s the code: https://codepen.io/goprime/pen/YJgLPM

First step is to reproduce the error, that makes it a lot easier to fix.

In your case if we load the pages one by one in order (1, 2, 3, 4…) then the comments are always loaded correctly.

But if you skip for example and loads the page 3, then it will fails. I see that you’re doing this:

First you create a list of all .comments:

commentSection = document.querySelectorAll('.comments');

Then you ask for the commentSection at the position val:
commentSection[val].innerHTML = dat;

val is the id of the post as we can see here: https://jsonplaceholder.typicode.com/comments?postId=${val}.

What’s happening is that when we load the page 3, our commentSection will have about 20 items (the page 1 and 3), and then we try to get the commentSection at val, and val will be larger than our array. In case we try to get comments for the post id 30, we’ll basically do this: commentSection[30], but our array have only 20 items. So innerHTML is really being called on undefined.