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