Goal : I am trying to set the alt and title for an img.
Problem : The problem is, it is dynamically created in a chat when a user uploads an image. There is no id for the image.
What I tried : I tried adding it to the innerhtml but nothing happens when I try to set the title for the image (it displays the English text, not the Spanish). I know the condition is correct because I have translated other static items inside the same if statement. But this img is being dynamically created. I see some SO articles mentioning jquery. But others say you don't need it and can do this through pure JS.
if(locale=='es'){
openLargerImageMsg = 'Haga clic para abrir una imagen más grande'; //Text I want to display
document.getElementById('largerImageID').title = openLargerImageMsg;
document.getElementById('largerImageID').alt = openLargerImageMsg;
}
var newMsgImg = document.createElement('img');
var newMsgContent = document.createElement('div');
newMsgContent.innerHTML = '<img id="largerImageID" src="/ImgUploads/' + message.UploadedFileName + '" onclick="ShowLargerUploadedFile(\'/ImgUploads/' + message.UploadedFileName + '\');" alt="Click to open larger image" title="Click to open larger image" /><span class="ChatMessageTimestamp">' + message.Timestamp + '</span>';
newMsg.appendChild(newMsgContent);
appendMessage(newMsg);
var appendMessage = function (objMsg)
{
objLiveChatLog.appendChild(objMsg);
};
I think that the problem is that you use the getElementById
function before that you create the element.
I write some test and this should work.
// Fake locale change locale = `es`; const genImg = () => { const newImg = document.createElement(`img`); newImg.alt = `Click to open a bigger image`; if (locale == `es`) { newImg.alt = `Haga clic para abrir una imagen más grande`; } document.body.appendChild(newImg); } document.getElementById(`button`).addEventListener(`click`, genImg);
<button id="button">Click</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.