How to return an image from http source in Javascript

I have a list of dictionaries containing data, where each dictionary has a key 'picture' and a value as an image source (http). 'picture': 'http://....'as well as other key:value sets.

I need to return a html page with a list of names and images associated with the dictionaries.

I have managed to return a list of names but when I try to return the images it returns the image source as a string.

function add_people(data) {
    var element = document.getElementById('people');

    var list = "<ul>";
        for (var i=0; i<data.length; i++) {
            list += "<li>"
                + data[i].name
                + data[i].picture
                + "</li>"
        }
    list += "</ul>";

    element.innerHTML = list
}

This function returns a list of names with the source for the images but not the images themselves, e.g.

  • Captain Pertsy://robohash.org/8c4b1b5a-bb8f-489b-8102-a1e9634627e0

Help is appreciated, thanks.

Answers:

Answer

you will need to add image tag inside list element to get the images

 function add_people(data) {
    var element = document.getElementById('people');

var list = "<ul>";
    for (var i=0; i<data.length; i++) {
        list += "<li>"
            + data[i].name
            + "<img src='"+data[i].picture+"' />"
            + "</li>"
    }
list += "</ul>";

element.innerHTML = list
 }
Answer

Use <img> tag to display your images from the source file. In <img> tag, set the source of the image in src attribute.

<img src="http://..." >
Answer

Use img tag

<img src=`${url}`>
Answer

Use the <img> element if you want to show an image. Use the src attribute to point the element to the source. Here is the modified source.

function add_people(data) {
    var element = document.getElementById('people');

    var list = "<ul>";
        for (var i=0; i<data.length; i++) {
            list += "<li>"
                + data[i].name                  
                + "<img src=\"" + data[i].picture + "\"></img>"
                + "</li>"

        }
    list += "</ul>";

    element.innerHTML = list
}

Additionally, you can use ES6 template strings to easily concatenate strings to build DOM.

list += `<li> ${data[i].name} <img src="${data[i].picture}"></img></li>`
Answer

You have to use the img tag and add the picture data as a src attribute. You can also enhance the readability of the code using literal string.

function add_people(data) {
    var element = document.getElementById('people');

    var list = "<ul>";
        for (var i=0; i<data.length; i++) {
            list += `<li>
                      ${data[i].name}
                      <img src="${data[i].picture}" />
                    </li>`
        }
    list += "</ul>";

    element.innerHTML = list
}


Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.