Estoy obteniendo datos de una API (TMDB) y creando una matriz para recorrer los datos, obtengo todo lo que quiero en la consola en el navegador, pero solo obtengo el último índice de la matriz cuando intento agregarlo al DOM. Gracias
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(); });El ciclo reemplaza el HTML interno de la etiqueta <p> con cada iteración, dejando solo el último visible cuando finaliza el ciclo. En lugar de reemplazar, puede agregar al html con += .
Ejecute el fragmento y presione el botón "Buscar" para ver...
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>Hay muchas otras formas de agregar al DOM, incluso agregando una nueva etiqueta para cada resultado de la API.
Para hacer eso, usaría appendChild() dentro del bucle, en lugar de solo al principio.