Sort comments block by oldest first

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>
1 Like

Thanks for sharing the code with @acjnas :star_struck:

Appreciate it a lot.

1 Like