Navbar show custom JS

Hi all, I need a little help to modify a script provided by @Teodor used to set the show class in a navbar when there is an active link inside it.

Initially I had only one navbar (NavTabelle) so with the ID it worked fine now instead I should look for the ID of the navbar that contains the active link and apply the show class

I am attaching script to edit

<script>
document.addEventListener("DOMContentLoaded", function() {
        var nestedNavLinks = document.querySelectorAll('.sb-sidenav-menu-nested.nav a');
    
        var hasActiveLink = Array.from(nestedNavLinks).some(function(link) {
            return link.classList.contains('active');
        });
    
        if (hasActiveLink) {
            var navCollapse = document.querySelector('#navTabelle');
            navCollapse.classList.add('show');
        }            
    });

Please try this:
Instead of the class (.sb-sidenav-menu-nested.nav a) assign the specific id in your querySelectorAll (for example your id is ‘NavTabelle’)

<script>
document.addEventListener("DOMContentLoaded", function() {
        var nestedNavLinks = document.querySelectorAll('#NavTabelle.nav a');
    
        var hasActiveLink = Array.from(nestedNavLinks).some(function(link) {
            return link.classList.contains('active');
        });
    
        if (hasActiveLink) {
            var navCollapse = document.querySelector('#navTabelle');
            navCollapse.classList.add('show');
        }            
    });

**I suppose that the structure hasn’t changed… You have to check it out

No my problem is that the specific ID must be dynamic, I have to retrieve the ID of the nav if there is an active link inside and set the show class

This sounds like the perfect task for ChatGPT, have you tried it?

Though I’d probably ignore the existing code and ask ChatGPT to create one from scratch (so it doesn’t become confused/biased)

No I haven’t tried it yet, I will soon… in the meantime, if you have any suggestions, thank you