Home > Blockchain >  Argument grabbing all ID's from Array
Argument grabbing all ID's from Array

Time:11-16

I'm making a moviefilter website for school. Now the last part is that I need to link the imdbID from my array to the movie posters on the screen. I made the links, the filter mechanics work but when I click on a poster all the ID's of that filter are being added to the end. Not just one.

My teacher says I can forEach trough the movieArray array and write everything I need in that loop. Can someone help me or look at my code what I'm doing wrong. I wrote 2 seperate functions now to create the arguments needed.

My code:

const addMoviesToDom = function (movieArray) {
    const movieList = document.querySelector("#movielist");
    movieList.innerHTML = "";

    const moviePoster = movieArray.map(item => {
        return item.Poster;
    });
    const imdbId = movieArray.map(item => {
        return item.imdbID;
    })

    moviePoster.forEach(element => {
        let newLi = document.createElement("li");
        let newLink = document.createElement("a");
        let images = document.createElement("img");
        images.src = element;
        newLink.setAttribute("href", "https://www.imdb.com/title/"   imdbId);
        newLink.setAttribute("target", "_blank");
        newLi.append(newLink);
        newLink.append(images);
        movieList.appendChild(newLi);
    })
};
addMoviesToDom(movies);

Thanks in advance, hopefully you guys understand what I'm trying to explain, this is all pretty new for me.

CodePudding user response:

imdbId is an array of all the IDs. When you concatenate that to "https://www.imdb.com/title/" it's turned into a string, which joins all the IDs with a , delimiter. So you're not setting the href to just the ID corresponding to the current moviePoster element.

You need to index the array to get the correct ID. forEach provides the array index as the second argument to the callback function, so you can change element => to (element, i) =>, and then use imdbId[i].

But a simpler way would be to skip creating the moviePoster and imdbId arrays, and just create all the elements from movieArray.

const addMoviesToDom = function(movieArray) {
  const movieList = document.querySelector("#movielist");
  movieList.innerHTML = "";

  movieArray.forEach(element => {
    let newLi = document.createElement("li");
    let newLink = document.createElement("a");
    let images = document.createElement("img");
    images.src = element.Poster;
    newLink.setAttribute("href", "https://www.imdb.com/title/"   element.imdbId);
    newLink.setAttribute("target", "_blank");
    newLi.append(newLink);
    newLink.append(images);
    movieList.appendChild(newLi);
  })
};
addMoviesToDom(movies);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related