4chan Post Sorter

Sorts posts in a 4chan thread by reply count

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name          4chan Post Sorter
// @namespace     4chan-post-sorter
// @description   Sorts posts in a 4chan thread by reply count
// @license       MIT
// @match         http://boards.4chan.org/*/*
// @match         https://boards.4chan.org/*/*
// @grant         GM_registerMenuCommand
// @version       1.0.2
// @author        asdaa
// @icon          https://4chan.org/favicon.ico
// ==/UserScript==

const parent = document.querySelector(".thread");

function getReplies(post) {
    const backlink = post.querySelector(".backlink");
    return backlink ? backlink.querySelectorAll(".quotelink").length : 0;
}

function getSorted(posts) {
   return posts.sort((a, b) => getReplies(b) - getReplies(a));
}

function sortPosts() {
   const posts = [...document.getElementsByClassName("postContainer replyContainer")];
   const sorted = getSorted(posts);
   parent.append(...sorted);
}

var sortBtn = document.createElement('a');
sortBtn.href = 'javascript:;';
sortBtn.innerText = 'Sort';
document.querySelector(".navLinks.desktop").appendChild(sortBtn);
sortBtn.insertAdjacentText('beforebegin', ' [');
sortBtn.insertAdjacentText('afterend', ']');
sortBtn.addEventListener("click", sortPosts, false);

GM_registerMenuCommand('Sort Posts by Reply Count', sortPosts);