I have a modal that displays API images within a modal, and I want the "Add To Favourites" link to be shown within the modal. So far, I can display the "title", "explanation" and "date" by using result.title etc. However when I use result.saveText to display the "add to favourites" as a HTML link is display undefined. How do I display the "Add To Favourites as an HTML link within the modal?
// Image
const image = document.createElement("img");
image.src = result.url;
image.alt = result.title + "<br>" + result.explanation + "<br>" + result.date;
image.loading = "lazy";
image.classList.add("card-img-top");
// Card Title
const cardTitle = document.createElement("h5");
cardTitle.classList.add("card-title");
cardTitle.textContent = result.title;
// Save Text
const saveText = document.createElement("p");
saveText.classList.add("clickable");
if (page === "results") {
saveText.textContent = "Add To Favorites";
saveText.setAttribute("onclick", `saveFavorite('${result.url}')`);
} else {
saveText.textContent = "Remove Favorite";
saveText.setAttribute("onclick", `removeFavorite('${result.url}')`);
}
There is nothing wrong with your code showing (except not appending it either to a parent element or document.body)
I check your model and I found that the saveText
doesn't append to any parent element or any document.body. The element of your code doesn't even has p
tag.
Your probably should use append
method to append it to either a parent element or a child element. In your situation, you probably should use cardTitle.appendChild(SaveText)
Doesn't even has p
tag in your whole body
:
document.querySelectorAll('img')[1].onerror = function(){
let div = document.createElement('div')
div.textContent = 'Link is invalid.'
document.body.appendChild(div)
}
<img src="invalid.jpg" alt ="<a href='https://www.w3schools.com'>Visit W3Schools.com!</a>">
<img src="invalid.jpg" >