I've read several posts about GetElementsByClassName but I am struggling to understand how to iterate through what it returns.
I am writing pure javascript code so that my navigation bar will take "fixed" positioning when the user scrolls. However, when this change occurs, the navigation bar list items need to change formatting so that their corners are curved on the bottom instead of the top. I need to iterate through the return of getElementsByClassName to change each constituent elements individually but my for loop doesn't work. Do I need a For ... In loop maybe?
What I learnt from other posts:
getElementsByClassName does NOT return an array. It returns an HTMLcollection.
this may be much easier with jQuery (I'm trying to learn JavaScript as I build this site so its important that I don't use jQuery at this point).
The code in the JSFiddle below will run if you remove the for loop that I am trying to use to iterate through the HTMLcollection.
TLDR: What should my for loop look like in order to iterate through the HTMLcollection in the following fiddle?
JSFiddle:
https://jsfiddle.net/mcgettrm/e8dabdkn/
Code:
window.addEventListener('scroll', function (evt) {
var distance_from_top = document.body.scrollTop;
if (distance_from_top <= 80) {
document.getElementById("navBar").style.position = "static";
document.getElementById("navBarList").style.borderBottom = "solid black 4px";
document.getElementById("navBar").style.borderTop = "initial";
}
else if(distance_from_top > 80) {
document.getElementById("navBar").style.position = "fixed";
document.getElementById("navBar").style.top = "0px";
document.getElementById("navBar").style.borderTop = "solid black 4px";
document.getElementById("navBarList").style.borderBottom = "initial";
var myCollection = document.getElementsByClassName("navBarLink");
var collectionLength = myCollection.length;
document.getElementById("consoleInfo").innerHTML = collectionLength;
document.getElementById("consoleInfo").innerHTML = myCollection[0];
for(var i = 0, i <= collectionLength, i++){
myCollection.item(i).style.borderTopLeftRadius = "initial";
myCollection.item(i).style.borderTopRightRadius = "initial";
myCollection.item(i).style.borderBottomLeftRadius = "1em";
myCollection.item(i).style.borderBottomRightRadius = "1em";
}
}
});