Home > Software design >  creating img src using JavaScript returns broken img
creating img src using JavaScript returns broken img

Time:10-12

I iterate some JSON in order to obtain URLs of images in order to display them in a table.

The JavaScript code I'm using to do so is ( I generate a table and then populate cells in each row where the first cell in the row is an image and all the rest are strings):

for (var i = 0; i < data.result.length; i  ) {
    var newRow = document.createElement('tr')
    newRow.classList.add('table-row')
    for (var j = 0; j < data.result[i].length; j  ) {
        if (j == 0){
            var newCell = document.createElement('img');
            newCell.src = data.result[i][j];
            console.log(data.result[i][j])
            newCell.style.width = 50;
            newCell.style.height = 50;
        } else {
            var newCell = document.createElement('td');
            newCell.classList.add('col')
            newCell.innerHTML = data.result[i][j];
        }
        newRow.appendChild(newCell);
    }
    table[0].appendChild(newRow)
}

Where data.result[i][j] contains the URL.

For example, In one of the cases I get:

newCell.src = 'https://oldschool.runescape.wiki/w/Mithril bar#/media/File:Mithril bar_detail.png'

Now, when I click on that URL it indeed displays me an image. However, when I use the code above Im getting a broken image:

enter image description here

Any reason that I won't show the image?

I thought maybe it is due to that preview on the website but not sure how to deal with it.

Thank you

CodePudding user response:

try newCell.src="https://oldschool.runescape.wiki/w/Mithril_bar#/media/File:Mithril bar_detail.png"

30 chars

CodePudding user response:

I think the URL is not really pointing to an image.

If you go to the link and right click on the image and "open image in new tab" you get this link:

https://oldschool.runescape.wiki/images/thumb/b/b5/Mithril_bar_detail.png/1280px-Mithril_bar_detail.png?c7a7b

CodePudding user response:

The image URL you provided is not rendered in the DOM. Try this one instead:

https://oldschool.runescape.wiki/images/b/b5/Mithril_bar_detail.png?c7a7b
  • Related