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);
});
}
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
I tried this code but it doesn't work, I tried to give it a string instead of a variable which worked. Thank you for your help but I think I should go with some other way to tackle this problem. Thank you
what do you mean by "I tried to give it a string instead of a variable"? What does
e.target.id
returns? can you log the element target id to see what you get in return? this works 100% to my end.The problem was in the markup. I gave the id to the 'a' tag whose child was the img tag and added an event listener on the 'a' tag, but it never got clicked, because of the img tag. Thank you so much for your help because of which I was able to figure out the problem.