function showMovies (dataMovie) {
const main = document.getElementById('main');
main.innerHTML = '';
for (let i = 0; i < dataMovie.length; i ) {
const newMovie = document.createElement('div');
newMovie.innerHTML =
`<div >
<img src="${url_poster dataMovie[i].poster_path}" alt="${dataMovie[i].title}-poster">
</div>
<div >
<h3>${dataMovie[i].title}</h3>
<div >
</div>
<p>${dataMovie[i].release_date}</p>
</div>
<div >
<h3>Synopsis:</h3><br>
<p>${dataMovie[i].overview}</p>
</div>`
main.appendChild(newMovie);
for (let j = 0; j < genresList.length; j ) {
dataMovie[i].genre_ids.forEach(id => {
if (genresList[j].id === id) {
let g = '';
const div = document.querySelector('.genres');
const p = document.createElement('p');
g = genresList[j].name;
p.innerHTML = `<p>- ${g} </p>`
div.appendChild(p);
}
});
}
}
I want to display all genres of one movie. When i get one movie i've got no problem, when i get more than one, the first takes all the genres and no genres are displayed for the others. movieData is my data.results of the api (tmdb).
CodePudding user response:
You are selecting the same .genres
all the time.
Try this please:
const div = newMovie.querySelector('.genres');
function showMovies(dataMovie) {
const main = document.getElementById('main');
main.innerHTML = '';
for (let i = 0; i < dataMovie.length; i ) {
const newMovie = document.createElement('div');
newMovie.innerHTML =
`<div >
<img src="{url_poster dataMovie[i].poster_path}" alt="{dataMovie[i].title}-poster">
</div>
<div >
<h3>{dataMovie[i].title}</h3>
<div >
</div>
<p>{dataMovie[i].release_date}</p>
</div>
<div >
<h3>Synopsis:</h3><br>
<p>{dataMovie[i].overview}</p>
</div>`
main.appendChild(newMovie);
for (let j = 0; j < genresList.length; j ) {
dataMovie[i].genre_ids.forEach(id => {
if (genresList[j] === id) {
let g = '';
const div = newMovie.querySelector('.genres');
const p = document.createElement('p');
g = genresList[j].name;
p.innerHTML = `<p>- ${g} </p>`
div.appendChild(p);
}
});
}
}
}
var genresList = [1,2,3,4,5,6,7,8]
showMovies([{genre_ids:[1,2,3]},{genre_ids:[4,5,6]}])
<div id="main"></div>
CodePudding user response:
The problem is that when you write const div = document.querySelector('.genres');
you are always selecting the first element on the page that matches the selector.
One idea would be to add an id to the movie container, which you can then use on your query. For instance something like this:
- when you create the container div:
const newMovie = document.createElement('div');
newMovie.classList.add('new-movie');
newMovie.setAttribute('movie-id', dataMovie[i].id);
- then on your selector:
const div = document.querySelector(`.new-movie[movie-id="${dataMovie[i].id}"] .genres`);
This would give you the .genres
div inside the correct container (instead of the first one on the page).
For a different approach you could also try to use
const div = newMovie.querySelector('.genres');
instead of
const div = document.querySelector('.genres');
Which should give you the same result