Sort comments block by oldest first [updated 2024]

I was in the need to sort the comments block showing the latest comment at the bottom of the stack to mimic a chat conversation.

Add a custom code block on your page and paste the following code:

<script>
    document.currentScript.parentElement.parentElement.parentElement.parentElement.parentElement.hidden = true;

    function sortElements(element, cont) {
        while(element.children.length >1){
            cont.insertAdjacentElement("afterbegin",element.children[1])
        }
        let itv2 = setInterval(()=>{
            if(element.children.length>1){
                window.clearInterval(itv2)
                while(element.children.length >1){
                    cont.insertAdjacentElement("afterbegin",element.children[1])
                }
            }
        },50)
    }
    let comments;
    let itv = setInterval(() => {
        comments = document.getElementsByClassName("sw-js-comments-container")[0]
        if (comments){
            window.clearInterval(itv)
            let container = document.createElement("div")
            comments.insertAdjacentElement("afterbegin",container)
            sortElements(comments, container);
            let showMore = document.getElementsByClassName("sw-comment-btn-wrapper MuiBox-root css-xi606m")[0]
            if(showMore){
                comments.insertAdjacentElement("beforebegin", showMore)
                showMore.children[0].addEventListener("click", ()=>{
                    sortElements(comments,container)
                })
            }
        }
    }, 100);
</script>
2 Likes

Thanks for sharing the code with @acjnas :star_struck:

Appreciate it a lot.

1 Like

This code isn’t working for me. Would you mind taking a look to see if any new updates have stopped the code working?

Here is code to sort comments “oldest first” for new comments block 2024:

<script>
document.addEventListener("DOMContentLoaded", function () {
    // Flag to avoid duplicate sorting
    let isSortingScheduled = false;

    // Store the original open method
    const originalOpen = XMLHttpRequest.prototype.open;

    // Override the open method to capture all AJAX requests
    XMLHttpRequest.prototype.open = function(method, url) {
        // Store the original send method for later use
        const originalSend = this.send;

        // Check if the request URL matches the patterns of interest
        if (url.includes('/v2/comments')) {
            // Add a custom property to the request to identify it later
            this._intercepted = true;

            // Override the send method to detect request completion
            this.send = function(body) {
                // Set up a handler for when the request completes
                this.addEventListener('load', function() {
                    if (this._intercepted) {
                        // Only schedule sorting if not already scheduled
                        if (!isSortingScheduled) {
                            isSortingScheduled = true;

                            // Run sorting script after a 1-second delay
                            setTimeout(() => {
                                runSortingScript();
                                isSortingScheduled = false; // Reset the flag after sorting
                            }, 1000);
                        }
                    }
                });

                // Call the original send method
                originalSend.call(this, body);
            };
        }

        // Call the original open method
        return originalOpen.apply(this, arguments);
    };

    // Define the sorting script
    function runSortingScript() {
        // Select the comments container
        const commentsContainer = document.querySelector('.sw-js-comments-container');
        
        if (commentsContainer) {
            // Select all individual comments blocks
            const commentBlocks = Array.from(commentsContainer.querySelectorAll('.MuiStack-root[data-resourceid]'));

            // Ensure there are comments to sort
            if (commentBlocks.length > 0) {
                // Reverse the order of comment blocks
                commentBlocks.reverse();

                // Clear the container and append the reversed comments
                commentsContainer.innerHTML = '';
                commentBlocks.forEach(block => commentsContainer.appendChild(block));
            }
        }
    }
});
</script>