2

I have a set of image links and I want to turn them into an image using JavaScript and the links are dynamic which are coming from an API. So how can I turn those links into an image. I want all the images to show for example: I have 7 image URLs so I want all the 7 URLs to get turned into an image and not only 1

The links are in a div like:

<div class="avatar"></div>

And the data is coming by an API using JS:

const getimage = () => {
    axios
        .get(
            "https://api.github.com/repos/owner/repo/contributors"
        )
        .then((response) => {
            const users = response.data;
            console.log(users)
            const avatar = document.querySelector(".avatar")
            avatar.innerHTML=users.map((u) => u.avatar_url).join("<br />");
        })
        .catch((error) => console.error(error));
};
getimage();

How can I do that

1
  • Show an example of what the links you've got and an attempt to make this work. We'll help you out. Commented Aug 1, 2021 at 10:16

1 Answer 1

5

You need to make a loop for all links and create image tag and then set src attribute and finally append to body.

Try this one:

var array = ["link1", "link2"];
array.forEach((t) => {
    var img = document.createElement("img");
    img.src = t;
    document.body.appendChild(img);
})

Update based on question

     var users = ["link1", "link2"];
     const avatar = document.querySelector(".avatar")
     users.map((u) => {
         var img = document.createElement("img");
         img.src = u.avatar_url;
         avatar.appendChild(img);
         avatar.innerHTML += `<br/>`;
     })
  <div class="avatar">

    </div>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.