Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

292
Visualizações
Javascript - For loop not iterating through last item when changing class name

I'm trying to change the classname if certain links in my navigation, but the doesn't seem to want to iterate through the last item. The commented out hardcoded section works just fine

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

The console returns

  • Worked 1 time(s)
  • Worked 2 time(s)
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's a live collection, meaning if you loop it and you change its collected items in the loop the loop will skip nodes here and there.

// 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

Live collections are synchronous and reflecting the current state of the collection. If you don't want this to happen you need static collection instead:

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

Now even if p[0].className = '' happens, that collection will still have that previously .p element in it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda