Show more/less for child levels in a hierarchical Checkboxes facet

<?php
add_action('facetwp_scripts', function () {
// Change "3" in both style and script to change the number shown initially

?>
    <style>
        .facetwp-depth.visible > div:nth-child(n+3 of .facetwp-checkbox) {
            display: none;
        }
        .facetwp-depth.visible.showmore > div:nth-child(n+3 of .facetwp-checkbox) {
            display: block;
        }
    </style>
    <script type="text/javascript">
        (function($) {
            document.addEventListener('facetwp-loaded', function() {
                document.querySelectorAll('.facetwp-depth').forEach((node) => {
                    if ( node.childNodes.length > 3 ) { // only works if no grandchildren
                        // add show more / less
                        let show = document.createElement('a');
                        show.textContent = 'Show more';
                        show.classList.add('show-more');
                        node.append(show);
                        show.addEventListener('click', function(e) {
                            let showmore = e.target;
                            let depth = e.target.parentNode;
                            if ( depth.classList.contains('showmore') ) {
                                depth.classList.remove('showmore');
                                showmore.textContent = "Show more";
                            } else {
                                depth.classList.add('showmore');
                                showmore.textContent = "Show less";
                            }
                        });
                    }
                });
            });
        })(fUtil);
    </script>
<?php
}, 100);