mostra (al più) 2 post in evidenza + migliorato HTML parser

This commit is contained in:
giomba 2021-02-16 12:18:41 +01:00
parent 1bb5d482b7
commit 1146232b9d
1 changed files with 20 additions and 13 deletions

View File

@ -172,23 +172,30 @@ function counters() {
fetch("https://golem.linux.it/wp/wp-json/wp/v2/posts?sticky=true")
.then(response => response.json())
.then(json => {
let article = document.getElementById("wp-featured-posts");
let ul = document.getElementById("wp-featured-posts");
if (json.length == 0) {
let text = document.createTextNode("Nessun articolo in evidenza");
article.appendChild(text);
ul.appendChild(text);
} else {
let post = json[0];
let a = document.createElement("a");
a.href = post.link;
a.appendChild(document.createTextNode(post.title.rendered));
article.appendChild(a);
let text = post.excerpt.rendered.replace(/<.*?>/g, '');
text = text.substr(0, text.indexOf('.') + 1);
text += ' [...]';
let textNode = document.createTextNode(text);
article.appendChild(document.createElement('br'));
article.appendChild(textNode);
for (let i = 0; i < json.length && i < 2; ++i) {
let li = document.createElement("li");
let post = json[i];
let a = document.createElement("a");
a.href = post.link;
a.appendChild(document.createTextNode(post.title.rendered));
li.appendChild(a);
/* create a temporary element to exploit the HTML parser of the browser
and then retrieve the HTML-tag-free purged text */
let elem = document.createElement("div");
elem.innerHTML = post.excerpt.rendered;
let text = elem.textContent || elem.innerText;
text = text.substr(0, text.indexOf('.') + 1);
let textNode = document.createTextNode(text);
li.appendChild(document.createElement('br'));
li.appendChild(textNode);
ul.appendChild(li);
}
}
})