Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

324
Vistas
I used fetch() method to load data from external server. All data are being loaded properly. But I came across dificulity when I use querySelector

I'm trying to load data from an external server and render it on my web page by using javascript. I used fetch(url) to load the data. Data is being loaded properly; I can see all of it in the console. What happens is that, when I use document.querySelector(), only 1 article is shown on my web page despite there being 10 articles. Then, I used document.querySelectorAll(), but nothing showed on my web page and there were no errors, no information in the console as well. What I did was this:

let url = "https://gnews.io/api/v4/top-headlines?lang=en&max=50&token=TOKEN_HERE";
    
fetch(url)
    .then(function(response) {
        return response.json();
    })
    .then(function(details) {
        let allArticles = details.articles;
        allArticles.forEach(function(article) {
            let header = document.querySelector('.heading');
            header.innerText = article.title;

            let description = document.querySelector('.description');
            description.innerText = article.description;

            let content = document.querySelector('.content');
            content.innerText = article.content;
        });
    });

HTML:

<body>
    <h4 class="heading"></h4>
    <p class="description"></p>
    <p class="content"></p>
    <!-- ... -->
</body>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You will need to generate DOM. Use your HTML structure as template for each article.

const buildArticle = (id, title, desc, content) => {
  return `
    <div id="article-${id}"">
    <h4 class="heading">${title}</h4>
    <p class="description">${desc}</p>
    <p class="content">${content}</p>
 </div>
`;
};

let url =
  "https://gnews.io/api/v4/top-headlines?lang=en&max=50&token=368273b6710cecf2476380400a7635c2";

fetch(url)
  .then(function (response) {
    return response.json();
  })
  .then(function (details) {
    let allArticles = details.articles;

    document.getElementById("app").innerHTML = allArticles
      .map(function (article, idx) {
        return buildArticle(
          idx,
          article.title,
          article.description,
          article.content
        );
      })
      .join("");
  });
<div id="app"></div>

alternate way

const createArticle = (id, title, desc, content) => {
  const article = document
    .querySelector("#article-template")
    .content.cloneNode(true);
  article.querySelector(".article").id = `article-${id}`;
  article.querySelector(".heading").textContent = title;
  article.querySelector(".description").textContent = desc;
  article.querySelector(".content").textContent = content;
  return article;
};

const url =
  "https://gnews.io/api/v4/top-headlines?lang=en&max=50&token=368273b6710cecf2476380400a7635c2";

fetch(url)
  .then((res) => res.json())
  .then((details) =>
    details.articles.forEach((article, idx) =>
      document
        .getElementById("app")
        .appendChild(
          createArticle(
            idx,
            article.title,
            article.description,
            article.content
          )
        )
    )
  );
<div id="app"></div>

<template id="article-template">
  <div class="article">
    <h4 class="heading"></h4>
    <p class="description"></p>
    <p class="content"></p>
  </div>
</template>;

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda