Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
Agregar clase activa basada en la URL actual

Estoy tratando de agregar una clase 'activa' en mi enlace. esta diciendo

 Uncaught TypeError: document.querySelectorAll(...).each is not a function

Aquí está mi código:

 const current = window.location.href; document.querySelectorAll("#nav-tab a").each(function(){ const $this = this; if($this.attr('href').indexOf(current) !== -1){ $this.classList.add("active"); } });

¿Me puedes ayudar? ¿O hay una mejor manera de agregar un nombre de clase basado en la URL actual? ¡Muchas gracias!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Creo que te equivocas jQuery y vanilla javascript

$.each es una función jQuery en su caso, puede usar .forEach

$.attr es una función jQuery en su caso, puede usar .getAttribute

 const current = "#test-3";//window.location.href; document.querySelectorAll("#nav-tab a").forEach((elem) => { if (elem.getAttribute('href').indexOf(current) !== -1) { elem.classList.add("active"); } });
 .active { color:red}
 <div id="nav-tab"> <a href="#test-1">Test 1</a> <a href="#test-2">Test 2</a> <a href="#test-3">Test 3</a> <a href="#test-4">Test 4</a> </div>

about 4 years ago · Juan Pablo Isaza Report

0

Tienes algunos problemas con tu código. Sus métodos jQuery principalmente confusos con los métodos/convenciones regulares del navegador nativo:

  1. Debe usar .forEach() y no .each() . El método .forEach() es un método en NodeList que querySelectorAll() .

  2. .attr() no es un método válido. Para obtener el atributo de un elemento, puede usar .getAttribute() . Podemos usar .href aquí para obtener el href. Tenga en cuenta que getAttribute("href") recuperará la URL tal como está en su marca, mientras que .href recuperará la completa, por ejemplo, si tuviera href="/foo/bar" , .href le dará https://example.com/foo/bar , mientras que .getAttribute() devolverá solo /foo/bar .

  3. Utilice el parámetro del elemento de la función en lugar de this . Cuando usa .forEach() , está iterando sobre los elementos en su NodeList (es decir, los elementos que seleccionó), por lo que puede acceder a cada uno usando el primer parámetro de la devolución de llamada forEach . this valor en el navegador (si no está en modo estricto ) se establecerá de manera predeterminada en window , por lo que no será el elemento que espera que sea:

 const current = window.location.href; document.querySelectorAll("#nav-tab a").forEach(function(elem){ if(elem.href.includes(current)){ elem.classList.add("active"); } });

También cambié .indexOf(...) !== -1 a .includes() , que es una forma más moderna de verificar si una cadena contiene otro valor.


Señalaré que puede hacer que su selector de consultas sea más avanzado, lo que limitará la cantidad de elementos que itera:

 const current = window.location.href; document.querySelectorAll(`#nav-tab a[href*="${current}"]`).forEach(elem => { elem.classList.add("active"); });

Esto usa el selector de atributo a[href*=...] para seleccionar los a que tienen un href que contiene el texto almacenado en el archivo current .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!