0

I want to create a new img Element in javascript when my forEach loop read any index of my array and this is the code

axios.get('https://jsonplaceholder.typicode.com/photos', {params: {_limit: 20}}).then(res => {
  let values = Object.values(res);
  values[0].forEach((item) => {
    document.getElementById('root').innerHTML = `<img src="${item.url}">`;
  }
})

enter image description here

2
  • 3
    Please don't link to your code on a 3rd party sites as links can die over time and PLEASE do not share pictures of your code, share the text of the code itself, right here in your question. Commented Feb 4, 2021 at 21:25
  • You need to share the full code as text, for both the Button and App component, preferably as a snippet because there are many ways to approach this problem. Commented Feb 4, 2021 at 21:50

1 Answer 1

0

I thought I would do a runnable version based on Mr Alien's (now deleted) answer. However, as pointed out by Vektor's comment this is likely not helpful (or at least not ideal) if you're working in something like React.

If you are working in something like React you would more likely want to setup state for the images array, render the images based on this array and setup something like a useEffect hook / componentDidMount method to load the images and update the state.

Runnable version based on Mr Alien's (now deleted) answer:

const ele_with_attributes = (tag, attributes = {}) => 
  Object.assign(document.createElement(tag), attributes);

const append_image_from_api = (item) =>
  document.getElementById('images').appendChild(
    ele_with_attributes('img', {
      src: item.thumbnailUrl, //item.url,
      alt: item.title
    })
  );

axios
  .get('https://jsonplaceholder.typicode.com/photos', {params: {_limit: 5}})
  .then(res => res?.data?.forEach(append_image_from_api));
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<div id="images"></div>

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.