0

I'm try to display multiple pictures from fetched JSON data in to DOM how can I perform this task efficient way ? (just using pure JS)

async function Data(){
    
    const response = await fetch('https://gist.githubusercontent.com/whichbuffer/c835320d7dcf9899a22890b0a3589d88/raw/97f9bb3d4e0c9d558cc5184eb21a12831895dfa4/IMDB.json');
    const data = await response.json(); 
    console.log(data.Contents);
    
    for(let i=0;i<data.Contents.length;i++){
        document.getElementById('Title').innerHTML +=("<br>" + data.Contents[i].Title + "<br>")
       document.getElementById('img').src += (data.Contents[i].Poster)
    }
}

Data().catch(error => {
    console.log("error!");
    console.error(error);
});
<img src="" id="img">
<p id="Title"></p>

2 Answers 2

1

This will append a <li> for each object in the array to the <ul>.

const list = document.getElementById("imglist")

async function Data() {
    //Fetch the JSON
    const response = await fetch('https://gist.githubusercontent.com/whichbuffer/c835320d7dcf9899a22890b0a3589d88/raw/97f9bb3d4e0c9d558cc5184eb21a12831895dfa4/IMDB.json');
    const data = await response.json(); 
    
    //Loop over the fetched array
    for(let i = 0; i < data.Contents.length; i++){
        //Create the `<li>`
        const li = document.createElement("li")
        
        //Create the `<p>` for the title and add it to the `<li>`
        const p = document.createElement("p")
        p.appendChild(document.createTextNode(data.Contents[i].Title))
        li.appendChild(p)
        
        //Create the `<img>` for the poster and add it to the `<li>`
        const img = document.createElement("img")
        img.src = data.Contents[i].Poster
        li.appendChild(img)
        
        //Add the `<li>` to the list
        list.appendChild(li)
    }
}

Data().catch(error => {
    console.log("error!");
    console.error(error);
});
<ul id="imglist"></ul>

Sign up to request clarification or add additional context in comments.

Comments

0

Could you dump your XHR Request /Json Response ?

1 Comment

yes I can you can see If you uncomment console.log(data.Contents)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.