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

97
Visualizações
Changing class attribute in JS for loop stops after 8 iterations

Total coding noob here. I got this HTML:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="display.js"></script>
</head>
<body>
<button type="button" onclick="SentenceInline()">Sentences = linline</button><br>
<button type="button" onclick="SentenceBlock()">Sentences = block</button></p>
<span class="sentence" id="first-p1-s1">Span 1</span>
<span class="sentence" id="first-p1-s2">Span 2</span>
…
<span class="sentence" id="first-p1-s9">Span 9</span>
<span class="sentence" id="first-p1-s10">Span 10</span>
<span class="sentence" id="first-p1-s11">Span 11</span>
<span class="sentence" id="first-p1-s12">Span 12</span>
</p>
</body>
</html>

…and this code in diplay.js:

function SentenceInline() {ChangeClassAttributes('sentence','inline');}
function SentenceBlock() {ChangeClassAttributes('sentence','block');}

function ChangeClassAttributes(FindClass,ChangeAttribute) {
var ClassToStyle = document.getElementsByClassName(FindClass);
for (let i = 0; i < FindClass.length; i++) { ClassToStyle[i].style.display = ChangeAttribute;}}

Clicking the Sentences = block button will change the display attribute of spans with class sentence for the first 8 <span> elements, then it stops. The remaining spans stay inline.

Can someone point out what I’m doing wrong here? Thank you.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You're using FindClass.length as the limit of your loop. FindClass is the first argument of your ChangeClassAttributes which is string sentence... which has a length of 8 :)

To fix this you'll need to change your loop to look something like this

for (let i = 0; i < ClassToStyle.length; i++) {
    ClassToStyle[i].style.display = ChangeAttribute;
}
about 4 years ago · Santiago Trujillo 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