Mi código:
const address = location.pathname; const links = document.querySelectorAll('.sidebarMain a'); links.forEach(function(el) { if(new RegExp(`^${el.getAttribute('href')}(.*)$`, 'i').test(address)) el.classList.add('active')});Pero no funciona, ¿dónde me equivoqué?
El HREF de los enlaces incluirá automáticamente el dominio actual al acceder a través de javascript, por lo que puede compararlo directamente con window.location.href
let links = document.querySelectorAll(".sidebarMain a"); let cur = window.location.href; console.log(cur) links.forEach(function(link){ if(link.getAttribute("href") == cur){ link.classList.add("active"); } }); .active{font-weight:bold;color:red;} <div class="sidebarMain"> <a href="https://stacksnippets.net/js">Active</a> <a href="aaa">test3</a> </div>