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

96
Views
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 answers
Answer question

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