Need some help with custom code to change language

Hello Everyone!

I am trying to make a custom code to switch the language of my website. The aim is to check the language setting of the browser and redirect. Or, if the user selected, then dont redirect but remember.

I did this (before )


<script>
document.addEventListener('DOMContentLoaded', function() {
    
    // Check if the user's preferred language is already set
    var userLangPreference = localStorage.getItem('userLangPreference');

    // If the userLangPreference is not set, detect the browser language and set it
    if (!userLangPreference) {
        var FullUserLang = navigator.language || navigator.userLanguage;
        var userLang = FullUserLang.slice(0, 2);

        // Set the user's preferred language in localStorage
        if (userLang === 'NL') {
            localStorage.setItem('userLangPreference', 'NL');
            window.location.replace('https://www.cobalt.solar/nl/home'); // Redirects to DUTCH version ONLY once
        } 
         if (userLang === 'DE') {
            localStorage.setItem('userLangPreference', 'DE');
            window.location.replace('https://www.cobalt.solar/de/home'); // Redirects to GERMAN version ONLY once
        } else {
            localStorage.setItem('userLangPreference', 'EN');
            window.location.replace('https://www.cobalt.solar/de/home'); // Redirects to GERMAN version ONLY once
        }
    }

    // Function to switch the language
    function switchLanguage(lang) {
        localStorage.setItem('userLangPreference', lang);
        window.location.reload(); // Reload the page to apply the language switch
    }

    // Get the button elements by their IDs
    var englishButton = document.getElementById('english-btn');
    var dutchButton = document.getElementById('dutch-btn');
    var germanButton = document.getElementById('german-btn');

    // Attach a click event listener to the buttons
    englishButton.addEventListener('click', function() {
        switchLanguage('EN'); // Calls switchLanguage with 'en' for English
    });
    
    dutchButton.addEventListener('click', function() {
        switchLanguage('NL'); // Calls switchLanguage with 'NL' for Dutch
    });
        
    germanButton.addEventListener('click', function() {
        switchLanguage('DE'); // Calls switchLanguage with 'DE' for German
    });
});
</script>

Also, i named the buttons. But i am not sure why this isnt working. Can someone help me figur out what the problem is?