Search code examples
javascriptstringimageasynchronous-messaging-protocol

weird URL deformation when changing src of <img>: & -> &amp


edit: It was Frontends fault. They made a copy of the img (for some mobile-version bs) including the id-attribute (facepalm) and didn't mentioned it. Thus my js worked correctly, but on the wrong element, which is hidden on desktop. Sorry.

Original post:

At some point in my code, I want to set the "src" attributes of several pictures in a grid.

I have a const array of URLs

const pictureURLs = [
    'https://firebasestorage.googleapis.com/projectname/o/main%2Fgrid%2Fthumbnail%2Fstudents.webp?alt=media&token=12345678',
    'https...'
];

and a simple forEach() loop

pictureURLs.forEach((pic, i) => {
    // let img = $(`#picture-grid-${i}`)[0];
    let img = document.getElementById(`picture-grid-${i}`);
    img.src = pic;
    img.onclick = () => {
        // some code..
    }
})

For some reasons this method works for hundreds of images, except one.

When I log the element "img", every occurrence of the URL is correctly saved in several Nodes, like "src" and "currentSrc". But only at "outerHTML" its src attribute is changed from "..media&token.." to "..media&amp;token"

All other URLs are fine in all other pictures. It's just this one.

I tried to reupload, assign new tokens and even changed from jquery to vanilla js. But it's only this one picture.

Can somebody help me to understand where this & -> &amp conversion happens? I've only found traces to jquery, but as I already wrote, I ruled this out.

Tested in Firefox and Chromium, both on Linux.


Solution

  • The conversion happens because in HTML an ampersand (&) is used for HTML entities, so to have a literal & you have to escape it.