Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
How to add class for ACTIVE URL in sidebar?

My code:

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')});

But it doesn't work, where did I go wrong?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The HREF of links will automatically include the current domain when accessing via javascript, so you can just directly compare to 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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda