0

I have a problem getting content and replacing the text using Reddit's subreddit Shower thoughts for data. What I'm trying to do is replace the h1 text with ID title to one from the JSON file but instead i get:

Uncaught SyntaxError: Unexpected number at the var thought.

This is my javascript file for changing the text

<script>
      $.ajax({
        url: 'https://www.reddit.com/r/showerthoughts/top.json',
        dataType: 'json',
        success: function( data )
        {
            var thought = data.children.0.data.title ;
            var author = data.children.'0'.data.author ;
    
            $('#title').text( thought );
        }
    });

  </script>

This is the HTML file that has the title.

 <body>
    <h1 class="title" id="title">Hello ! It's me</h1>
    <h5 class="author">- author</h5>
    <video autoplay loop poster="forest.jpeg" id="bgvid" controls muted>
        <source src="walk.mp4" type="video/mp4">
    </video>
    </body>
MatejMecka
  • 1,448
  • 2
  • 24
  • 37

2 Answers2

0

You can't do data.children.0, use data.children[0]. Anything after a dot has to be a valid identifier, and they cannot start with numbers.

See What characters are valid for JavaScript variable names?

Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

In order to access an array element, you'll have to use bracket notation like so:

var thought = data.children[0].data.title;
var author = data.children[0].data.author;

EDIT, This should work. You will receive a response object, not the data itself. The data can be found at response.data:

<script>
    $.ajax({
        url: 'https://www.reddit.com/r/showerthoughts/top.json',
        dataType: 'json',
        success: function(response)
        {
            var thought = response.data.children[0].data.title ;
            var author = response.data.children[0].data.author ;

            $('#title').text(thought);
        }
    });
</script>
Thomas Maddocks
  • 1,355
  • 9
  • 24