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

83
Vistas
appending data from Api to the Dom

I am fetching data from an API (TMDB) and creating an array to loop through the data, I get everything that I want in the console in the browser but I only get the last index of the array when I try to append it to the DOM. Thank you

const serachbtn = document.querySelector('.search');
const input = document.querySelector('input');

const p = document.createElement('p');
document.body.appendChild(p);


let movieArray = [];


async function getmovie(){

    const inputValue = input.value;

    const apiUrl = `https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&query=${inputValue}`;

    try{

        const response = await fetch(apiUrl);
        const movie = await response.json();

        //const picture = "https://image.tmdb.org/t/p/w500/" + movie.results[0].poster_path;
        
        let movieArray = movie.results;

        movieArray.forEach(searchie => {
            
            console.log("title: "+searchie.original_title);
            console.log("Overview: "+searchie.overview);
            
            p.innerHTML = searchie.original_title;

        });
        
    }catch(error){

        console.log('something went wrong');
    }
}

serachbtn.addEventListener('click', (e)=>{

    e.preventDefault();
    getmovie();

    });

enter image description here

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

The loop replaces your <p> tag's innerHTML with each iteration, leaving only the last one visible when the loop ends. Instead of replacing, you can append to the html with +=.

Run the snippet and press the "Search" button to see...

const serachbtn = document.querySelector('.search');
const p = document.createElement('p');
document.body.appendChild(p);

async function pretendFetch() {
  const movies = [
    { original_title: 'The Godfather' },
    { original_title: 'Star Wars' },
    { original_title: 'Jaws' },
  ];
  return Promise.resolve(movies);
}

async function getmovie() {
  try {
    const movieArray = await pretendFetch();
    movieArray.forEach(searchie => {
      console.log("title: " + searchie.original_title);

      // this is the important change: append, don't replace
      p.innerHTML += searchie.original_title + '<br/>';
    });
  } catch (error) {
    console.log(error);
  }
}

serachbtn.addEventListener('click', (e) => {
  e.preventDefault();
  getmovie();
});
<button class="search">Search</button>

There are numerous other ways to add to the DOM, including by adding a new tag for each API result.

To do that, you'd use appendChild() within the loop, instead of just at the start.

about 4 years ago · Santiago Gelvez 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