This piece of script has been passed around on Tumblr for years, to shorten the display note-count on blog posts:
var $container = $(".content");
$container.find(".notecount").each(function () {
var n = $(this).html().split(" ")[0].replace(/,/g, "");
if (n > 999) {
n = Math.floor(n / 100) / 10;
$(this).text(n + "k notes");
}
});
I'm fairly new-ish to js, but I find it a bit overkill to implement jquery to change (up to) 15 numbers on a page just for that neat trick, and was wondering if I could do without.
The following is mostly adapted from this codepen but 1, I know it's only affecting the first class on every page (I tried getElementsByClassName and querySelectorAll) and 2, my gauge is that I possibly will need to loop it - don't know how to loop the function so I'm questioning whether or not that's doable as is:
var tnotes = document.querySelector(".notecount");
function ShortenIt(value) {
var retVal = "";
if (value < 2) {
retVal = String(value) + " note";
}
if (value >= 2 && value < 1000) {
retVal = value + " notes";
}
if (value >= 1000 && value < 1000000) {
retVal = Math.round(value / 1000) + "k notes";
}
if (value >= 1000000 && value < 1000000000) {
retVal = Math.round(value / 1000000) + "m notes";
}
tnotes.innerHTML = retVal;
}
ShortenIt(tnotes.innerText);
Structure of each post:
<article class="post {PostType}" id="{PostID}">
<div>post content</div>
<div class="info">
<div class="notecount"><a href="{Permalink}">{NoteCount}</a></div>
</div>
</article>
I've gone through quite a few questions/answers on here, but I either came up short, or, still had trouble with targeting only the note count and not random numbers in a blog post. Any help or direction would be highly appreciated.
All of those jQuery methods are available in vanilla JS in one form or another (jQuery, after all, is just an abstraction on top of these DOM manipulation methods). Check out the MDN docs for some common ways to iterate over an array.
const convertNoteCounts = () => {
// querySelectorAll returns a NodeList...
const myListOfElements = document.querySelectorAll(".notecount");
// ... so we'll convert it to an Array and iterate over it
Array.from(myListOfElements).forEach((noteCountEl) => {
// grab the first child, which in our DOM will always be an <a /> element
let element = noteCountEl.children[0];
let n = Number(element.innerText.split(" ")[0].replace(/,/g, ""));
if (n > 999) {
n = Math.floor(n / 100) / 10;
element.innerText = `${n}k`;
}
})
}
<article class="post {PostType}" id="{PostID}">
<div>post content</div>
<div class="info">
<div class="notecount"><a href="#">863</a></div>
<div class="notecount"><a href="#">102</a></div>
<div class="notecount"><a href="#">1,400</a></div>
<div class="notecount"><a href="#">9,459</a></div>
<div class="notecount"><a href="#">12,450</a></div>
</div>
<button onclick="convertNoteCounts()">Convert!</button>
</article>