Warm tip: This article is reproduced from serverfault.com, please click

SRC attribute does not accept variables in javascript

发布于 2020-11-29 11:17:13

Is there any way to make the src attribute of document.createElement accept a variable?

I want to create a modal which pops up when an image is clicked and the image clicked is shown in full screen. But the src attr does not accept a variable.

let fScreenImgViewVar = document.getElementsByClassName('fullScreenViewLink');
for (let i = 0; i < fScreenImgViewVar.length; i++) {
    fScreenImgViewVar[i].addEventListener('click', (e) => {
        let imgElem = document.createElement('IMG');
        // here the src attr does not take the variable
        imgElem.src = e.target.id;
        console.log(imgElem)
        document.getElementById('fScreenImgView-img').appendChild(imgElem);
    });
}
Questioner
Apoorva Kumar Shukla
Viewed
0
rags2riches 2020-11-29 19:51:59

One of the things you could try to solve this problem is to use the setAttribute() method on he newly created image, as such:

let fScreenImgViewVar = document.getElementsByClassName('fullScreenViewLink');
for (let i = 0; i < fScreenImgViewVar.length; i++) {
  fScreenImgViewVar[i].addEventListener('click', (e) => {
    let imgElem = document.createElement('img');
    imgElem.setAttribute("src", `${e.target.id}`);
    // console.log(imgElem)
    document.getElementById('fScreenImgView-img').appendChild(imgElem);
  });
}

if this answer helps you solve the issue, please consider to accept the answer