Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading