Ive been trying to pull data from an "Current News Source" API structured in JSON using Javascript. Im in the testing phases right now.
On click I want to have my HTML element named "title" updated to the "title from the News JSON file. Heres what I have so far..
The HTML
<h3 class="title text-center" id="title" name="title">Russia accuses US of interfering in vote</h3>
<button type="button" class="btn btn-outline-dark text-white bg-muted" id="searchButton">Search</button>
The Javascript
const title = document.getElementById("title");
const searchButton = document.getElementById("searchButton");
searchButton.addEventListener("click", getRandomTitle)
function getRandomTitle() {
fetch('https://api.currentsapi.services/v1/latest-news?q=keywords=Biden&apiKey=12345678910')
.then(res => res.json())
.then(data => {
title.innerHTML = data.news.title
});
}
The JSON file
{
"status": "ok",
"news": [
{
"id": "4e67842f-018d-4744-aa02-d21da55c278d",
"title": "Early Matter Domination from Long-Lived Particles in the Visible Sector. (arXiv:2108.13136v2 [hep-ph] UPDATED)"
...
data.news is an array of object, to access the specific title you have to use the corresponding index.
Also, I will suggest you to use HTMLElement.innerText or Node.textContent to set the plain text (not htmlString) to a HTML element:
title.textContent = data.news[0].title; // get the title from first news object
From the JSON file, it looks like data.news is an array.
Try data.news[0].title
Try to use data.news[0].title because it seems you are getting array of object as result in data.news
function getRandomTitle() {
fetch('https://api.currentsapi.services/v1/latest-news?q=keywords=Biden&apiKey=12345678910')
.then(res => res.json())
.then(data => {
title.innerHTML = data.news[0].title // Specify the index for the array
});