I am using an API which gives me 70-ish projects. From these projects I need to show the title, image and tagline on a website. I managed to get the data on the website, but right now it shows the data as follows:
- Titles
- Images
- Taglines
Which means that right now I’m seeing 70 titles, then 70 images, then 70 taglines. I, of course, want this to be shown per project, so one title, one image, one tagline. This then should repeat for every project.
My code:
function fetchProjects(url) {
fetch(url)
.then(response => {
return response.json();
})
.then(data => {
appendData(data.data);
})
.catch(error => {
console.log(error);
});
}
function appendData(data) {
for (let i = 0; i < data.length; i++) {
let h3 = document.createElement('h3');
h3.innerHTML = data[i].project.title;
document.getElementById('project__header').appendChild(h3);
let img = new Image();
img.src = data[i].project.header_image;
document.getElementById('project__image').appendChild(img);
let p = document.createElement('p');
p.innerHTML = data[i].project.tagline;
document.getElementById('project__tagline').appendChild(p);
}
}
fetchProjects('api_url');
I tried reformatting my code but that didn’t work. I also tried Googling this but I didn’t get any results that could help me, so I probably didn’t use the right keywords. My apologies.
Can anyone point me to a clean way I can achieve this in plain Javascript and HTML? Thanks!
EDIT: Of course I don’t want to have to make 70 unique ID’s and solving it like that, I know it’s possible but it’s definitely not the clean solution I’d presume
2
Answers
Inside your for loop, you’re appending the items to the same element, so if you have:
after two cycles you’ll have
You should append them to the same element, or create a div and then append the entire div, something like:
you append all the titles to the ‘project__header’ div, images to the ‘project__image’ div, and tag-lines to the ‘project__tagline’ div. If I do this, it could be