Can't retrieve data from the NY Times API

后端 未结 2 1567
暖寄归人
暖寄归人 2021-01-07 10:46

I\'m trying to get the largest image, title, short description and url of top stories from the NY Times API. Before I get

相关标签:
2条回答
  • 2021-01-07 11:20

    Well, you created your element, but you still need to add it to the DOM.


    To create your element:

    const title = document.createElement('h1')

    And to add it to the DOM (to make it actually appear on your page):

    document.body.appendChild(title)


    But now you still need to add your actual title from the API to it:

    title.innerText = articles[i].title

    And all together:

    const title = document.createElement('h1') // create the heading
    title.innerText = articles[i].title // add the title from the API to your heading
    document.body.appendChild(title) // add your heading to the DOM (this will make it appear)
    
    0 讨论(0)
  • 2021-01-07 11:38

    Have a look at this. I answered in your dupe but here is better

    let html = [];
    fetch('https://api.nytimes.com/svc/topstories/v2/science.json?api-key=yourApiKey')
      .then((resp) => resp.json())
      .then(function(data) {
        data.results.forEach(res => {
          html.push(`<h1>${res.title}</h1>`);
        })
        document.getElementById("res").innerHTML = html.join("");
      })
    
    <div id="res"></div>
    
    0 讨论(0)
提交回复
热议问题