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.
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;
}