I have several links on my page and a function that generates the preview of each one like this:
Its supposed to loop and generate the preview for each link but it only does it one. Why is that?
function parselinks() {
var links = document.getElementsByClassName('linkprev');
for(var link of links) {
if(link.innerHTML =='') {
var data = {key: 'fe2964d7c80ef2b8f6ba046ae9e8c0a5', q: link.getAttribute('href') }
fetch('https://api.linkpreview.net', {
method: 'POST',
mode: 'cors',
body: JSON.stringify(data),
}).then(res => res.json()).then(response => {
var linktitle = response.title;
var linkdesc = response.description;
var linkimg = response.image;
link.innerHTML = `
<span><img src="${linkimg}" alt=""></span>
<h2>${linktitle}</h2>
<br>
<p>${linkdesc}</p>
`;
})
}
}
}
parselinks();
img {width:100px;}
span {
float: left;
}
span, h2, p {
font-size: 15px;
line-height: 80%;
}
<a href="https://yahoo.com" class="linkprev"></a>
<a href="https://facebook.com" class="linkprev"></a>
<a href="https://twitter.com" class="linkprev"></a>
<a href="https://instagram.com" class="linkprev"></a>