Hello, I'm new to Javascript and I'm stuck with my JS code.
I used fetch to reach my info and got it when I console logit but can't place the pics on my Html page. The pics are stored in an Array and I think I should use a for each code but can't manage it.
See my JS code below. If someone could give me a hint I would be very grateful.
Thanks in advance Hindrik
const button = document.querySelector("button");
const header = document.querySelector("h2");
button.addEventListener("click", () => {
fetch("http://172.104.246.137:8083/")
.then(result => result.json())
.then(data => {
console.log(data);
});
});
});
Top comments (8)
Here comes the right code that solved everything
´const button = document.querySelector("button");
const header = document.querySelector("h2");
button.addEventListener("click", () => {
fetch("172.104.246.137:8083/")
.then(result => result.json())
.then(data => {
console.log(data);
data.forEach(function(obj){
console.log(obj);
console.log(obj.url);
let img = document.createElement('img');
img.src = obj.url;
document.body.appendChild(img);
what does your data looks like? can you send a json example?
by the way, please add 3 backticks before and after your code snipped, (it is markdown format). then your code is easyer to read on the internet.
Thanks for your comment, will do that in the future
Problem solved:)
I know it's an array with tree pictures but don't know how to show them on the HTML page. I thought that I could use a for each loop but don't know how to catch the pictures in the array and Im really frustrated most because my knowledge is so bad.
(3) [{…}, {…}, {…}]
0: {filename: "1280px-Morning_at_Tham_Sakoen.jpg", caption: "Morning at Tham Sakoen National Park, Phayao Province, Thailand", attribution: "BerryJ, CC BY-SA 4.0 creativecommons.org/licenses/by-sa..., via Wikimedia Commons", about: "commons.wikimedia.org/wiki/File:Mo...", url: "upload.wikimedia.org/wikipedia/com...}
1: {filename: "Good_Morning_From_the_International_Space_Station.jpg", caption: "NASA astronaut Scott Kelly took this photograph of a moonrise over the western united states.", attribution: "Scott Kelly, Public domain, via Wikimedia Commons", about: "commons.wikimedia.org/wiki/File:Go...", url: "upload.wikimedia.org/wikipedia/com...}
2: {filename: "Morning_in_Langtang.jpg", caption: "A view of Langtang National Park from Laurebina-La Pass, Nepal", attribution: "Q-lieb-in, CC BY-SA 4.0 creativecommons.org/licenses/by-sa..., via Wikimedia Commons", about: "commons.wikimedia.org/wiki/File:Mo...", url: "upload.wikimedia.org/wikipedia/com...}
length: 3
proto: Array(0)
header.innerText
doesn't work? What are the code you have tried?Thanks for your suggestion I have tried alert append and for each and I think for each is the right one but how to catch pictures in the data array?/H