Skip to content Skip to sidebar Skip to footer

How To Iterate Through The Getelementbyclassname Return

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 navigat

Solution 1:

Regarding what you actually asked...

...which was how to loop through the collection:

You have a bunch of options, most of which are outlined in this answer under "For Array-Like Objects".

Briefly, some choices, assuming we start with:

var myCollection = document.getElementsByClassName("navBarLink");

forEach:

// forEach:Array.prototype.forEach.call(myCollection, function(element) {
    // Use element here
});

for loop:

vari;
for (i = 0; i < myCollection.length; ++i) {
    // Use myCollection[i] here
}

Note that that's 0 through < myCollection.length, not<= myCollection.length.

Or get a true array using Array.from or Array.prototype.slice. Details in the linked answer.

Regarding what you're actually doing...

I would strongly recommend that you not do a huge amount of inline styling like that. Instead, your JavaScript could be this simple:

window.addEventListener('scroll', function (evt) {
  var distance_from_top = document.body.scrollTop;
  document.body.classList.toggle("near-top",     distance_from_top <= 80);
  document.body.classList.toggle("not-near-top", distance_from_top > 80);
});

(If you have to support really old browsers, you'll need a classList shim or just manipulate body.className directly.)

Then, do the rest in your CSS, for instance your #navBar stuff:

body.not-near-top#navBar {
    /* styles for when we're not near the top */
}
body.near-top#navBar {
    /* style for when we are near the top */
}

Technically, you can do away with one of those classes if you like, just style based on body #navBar { ... } and then override in the class you keep.

Post a Comment for "How To Iterate Through The Getelementbyclassname Return"