Home > database >  Showing a forEach in HTML Element
Showing a forEach in HTML Element

Time:12-03

Im fetching a group of documents in a forEach from Firestore, I know im fetching this all as I can see documents and is fields in the console.

But when I add the id to the field fetched it only shows one document. (it should be 5 tiles and images but I can only see one)

From reading I know I only need to some how duplicate the HTML code based on the documents fetch in the collection but am struggling to do so.

Javascript code

const i = query(collection(db, "teams"));
const unsubscribe = onSnapshot(i, (querySnapshot) => {
            
     querySnapshot.forEach((doc) => {
          const docData = doc.data();

  document.getElementById("ageGroup").innerText = docData.ageGroup,
                document.getElementById("teamImage").src = docData.teamImage,
           
                
                console.log("Current data: ", docData);
                
            });

        });

HTML Code

<section class="teams">
            <article>
                <h1 class="team-names" id="ageGroup"></h1>
                <div class="team-line"></div>
                <img class="team-image" id="teamImage">

            </article>
</section>

CodePudding user response:

Unless you know how many items will be in the result in advance, dynamically create new elements inside the loop, and then insert the data from the database into the HTML.

Don't use IDs - those should only be used for absolutely unique elements, not for repeated elements.

For an <article> for each item, where the parent of all articles is the .teams, do:

const teams = document.querySelector('.teams');

querySnapshot.forEach((doc) => {
    const docData = doc.data();
    const article = teams.appendChild(document.createElement('article'));
    article.innerHTML = `
        <h1 class="team-names"></h1>
        <div class="team-line"></div>
        <img class="team-image">
    `;
    article.children[0].textContent = docData.ageGroup;
    article.children[2].src = docData.teamImage;
});
  • Related