0

I have a problem on how to display images in html table.

Based on the code below, the Image column only display the link of the image and not the image itself. How can I display the actual image into my Image column?

enter image description here

 root.on('child_added', function(childSnapshot) {
        rootRef10 = childSnapshot.val();
        var tr = document.createElement('tr');
        tr.appendChild(createCell(imageUrl));
        tr.appendChild(createCell(videoUrl));
        table.appendChild(tr);
    });

  function createCell(text) {
        var td = document.createElement('td');
        td.appendChild(document.createTextNode(text));
        return td;
    }
2
  • Please provide the code for your createCell() method Commented Sep 15, 2019 at 11:20
  • @tvicky4j247 I already update the code Commented Sep 15, 2019 at 11:22

1 Answer 1

1

Try using this:

// put your image url as the url parameter
function createImageCell(url) {
    var td = document.createElement('td');
    var img = document.createElement("img");
    img.src = url;
    td.appendChild(img);
    return td;
}

So basically replace tr.appendChild(createCell(imageUrl)); with tr.appendChild(createImageCell(imageUrl));

EDIT: If you want to set the width and height, you could do either:

function createImageCell(url) {
    var td = document.createElement('td');
    var img = document.createElement("img");
    img.src = url;
    img.width = 800; // specify width here
    img.height = 800; // specify height here
    td.appendChild(img);
    return td;
}

Or if you want varying widths and heights for each image, you could do:

function createImageCell(url, width, height) {
    var td = document.createElement('td');
    var img = document.createElement("img");
    img.src = url;
    img.width = width;
    img.height = height;
    td.appendChild(img);
    return td;
}

And then specify the width and height for each image whenever you call the method.

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

7 Comments

How can I set the image width and height?
Basically add img.width = width and img.height = height to the createImageCell function
One more question, why I cannot use the same code to display video?
Video playback requires a different tag, the <video> tag. The <img> tag only works for images.
You could display a placeholder image, or just leave the cell blank by first checking if the image url is null or empty before calling the createImageCell method. So do something like if (url) { createImageCell(url); } else { // just create and return var td without any of the img stuff }
|

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.