0

I have a script that runs on a page. It doesn't work, but when I type it into the console then run it it works perfectly.

This might sound like other questions such as this one, but I already have $(document).ready(). All the variables already defined here have been defined earlier in the document.

$(document).ready(function(){
    for (var i = 0; i < posts.length; i++) {
        var post_html = posts_html[i];
        var link = posts[i];
        console.log(i);
        name = $(post_html)[5].childNodes[1].innerHTML;
        document.getElementsByClassName('posts')[0].innerHTML = document.getElementsByClassName('posts')[0].innerHTML + '<a href="' + link + '" class="sidebar_link sidebar_posts_link"><li>' + name + '</li></a>'
        console.log(name + ' - ' + posts + ' - ' + i + ' - ' + posts[i] + ' - ' + link);

    }
});
Community
  • 1
  • 1
Ethan
  • 3,410
  • 1
  • 28
  • 49
  • 1
    What is `posts`? Also, please add the `HTML` too. – Ionut Necula Dec 09 '16 at 09:17
  • make sure you have jQuery included, also check the console for any errors. – Kevin Kloet Dec 09 '16 at 09:19
  • Do you have any errors in console? – rick Dec 09 '16 at 09:20
  • @Ionut I have a page which loads lots of different pages. here is the repository: https://github.com/Booligoosh/blog the js from my question is in end_script.js. The pages I'm running it on is posts/test2.html – Ethan Dec 09 '16 at 09:22
  • @rick I have "Uncaught ReferenceError: posts is not defined(…)" but when I type posts into the console it shows me something. After that I have "Uncaught TypeError: Cannot read property 'childNodes' of undefined(…)" – Ethan Dec 09 '16 at 09:31
  • at the momemt of execution posts is not defined. At this point which is the order of your scripts import? can you post the html with a short import description? – rick Dec 09 '16 at 09:34

1 Answers1

1

Add setTime out function in your code.please try below code:

$(document).ready(function(){  setTimeout(function(){
for (var i = 0; i < posts.length; i++) {
    var post_html = posts_html[i];
    var link = posts[i];
    console.log(i);
    name = $(post_html)[5].childNodes[1].innerHTML;
    document.getElementsByClassName('posts')[0].innerHTML = document.getElementsByClassName('posts')[0].innerHTML + '<a href="' + link + '" class="sidebar_link sidebar_posts_link"><li>' + name + '</li></a>'
    console.log(name + ' - ' + posts + ' - ' + i + ' - ' + posts[i] + ' - ' + link);

}
},5000);});
Sarika Koli
  • 773
  • 6
  • 11