Search code examples
javascripthtmlhyperlinkinnerhtml

HTML: Is there a way to display a link preview when setting innerHtml?


I'm setting the innerHtml property of an element using javascript. This is the innerHtml I'm setting which sends the link in an a-tag so that it's clickable:

description.forEach((pair) => {
   const [name, link] = pair;
   const htmlLink = `<a href=${link}>${link}</a><br><br>`
   const htmlPair = [name, htmlLink]
   joinedDescription.push(htmlPair.join(" "))
})

It's being displayed like this: enter image description here

Is there a way to have the link preview displayed so it looks like this instead:enter image description here


Solution

  • As for HTML itself, no there is no way to do that. Somebody created that the CSS for links to be displayed like that. There might be some libraries that do that, but I'm not sure. Unfortunately, you probably have to make it your own. For the video, you have to use JavaScript to check if a link is a YouTube video and embedded properly in iframe (use embed from YouTube). For the other links, you have to get the title / meta data and wrap it in a CSS container.