“How to use JavaScript to detect which page is open so it can assign a class to the correct element?

I am creating side menu, and I am trying to create javascript, that detect on what page I am on, and to add class active to the right element.

I have this html:

<div>
  <ul>
    <li> <a href="link1.html" className="menuLink"> Page 1 </a></li>
    <li> <a href="link2.html" className="menuLink"> Page 2 </a></li>
    <li> <a href="link3.html" className="menuLink"> Page 3 </a></li>
  </ul>
</div>

And ChatGpt sugestet this code for javascipt:

const currentPath = window.location.pathname;

document.querySelectorAll('.menuLink').forEach((link) => {
    
    if (link.getAttribute('href') === currentPath) {
        link.classList.add('active'); 
    }
});

Sadly it is not working. Any sugestions? Thank you.