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

290
Views
Javascript: el bucle For no itera a través del último elemento al cambiar el nombre de la clase

Estoy tratando de cambiar el nombre de clase si hay ciertos enlaces en mi navegación, pero parece que no quiere repetir el último elemento. La sección codificada comentada funciona bien

HTML

 <ul id="nav-list"> <li class="not-current"><a href="home.html">Home</a></li> <li class="current"><a href="documentation.html">Documentation</a></li> <li class="not-current"><a href="designs.html">Designs and Wireframes</a></li> <li id="last-nav-item" class="not-current"><a href="meeting.html">Book a Meeting</a></li> </ul>

JavaScript

 var notCurrentLinks = document.getElementsByClassName('not- current'); function openMobileMenu() { for (let i = 0; i < (notCurrentLinks.length); i++) { console.log('Worked ' + (i + 1) + ' time(s)'); notCurrentLinks[i].className = 'm-not-current'; } //Hardcoding below seems to work //notCurrentLinks[0].className = 'm-not-current'; //notCurrentLinks[1].className = 'm-not-current'; //notCurrentLinks[2].className = 'm-not-current'; notCurrentLinks = document.getElementsByClassName('m-not- current'); }

la consola vuelve

  • Trabajó 1 vez(es)
  • Trabajó 2 veces
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Es una colección en vivo, lo que significa que si lo repite y cambia los elementos recopilados en el ciclo, el ciclo omitirá nodos aquí y allá.

 // example document.body.innerHTML = '<p class="p">p</p><p class="p">p</p>'; const p = document.getElementsByClassName('p'); p.length; // 2 p[0].className = ''; p.length; // 1

Las colecciones en vivo son sincrónicas y reflejan el estado actual de la colección. Si no desea que esto suceda, necesita una colección estática en su lugar:

 // all o with class `p` const p = document.querySelectorAll('.p');

Ahora, incluso si sucede p[0].className = '' , esa colección aún tendrá ese elemento .p anterior.

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!