Why does my scroll function work with IDs but not classes?

تبليغ
سؤال

يرجى شرح بإيجاز لمإذا تشعر أنك ينبغي الإبلاغ عن هذا السؤال.

تبليغ
‎إلغاء

I’m trying to add (not replace) a class to multiple elements when scrolling down 10px. I need to target multiple IDs in some HTML that I have no way of changing. These elements do share a few classes though, so I thought I could just target one of those instead.

When I use getElementById, it runs just fine and adds a class to a single ID. If I use getElementsbyClassName or querySelectorAll to target a class, it won’t work.

This one works:

tabs = document.getElementById(“intro”);

scrollFunc = function() {
var y = window.scrollY;
if (y >= 10) {
tabs.classList.add(“scrollNav”);
}
else {
tabs.classList.remove(“scrollNav”);
}
};

window.addEventListener(“scroll”, scrollFunc);

This one doesn’t:

tabs = document.getElementsByClassName(“navTabs”);

scrollFunc = function() {
var y = window.scrollY;
if (y >= 10) {
tabs.classList.add(“scrollNav”);
}
else {
tabs.classList.remove(“scrollNav”);
}
};

window.addEventListener(“scroll”, scrollFunc);

‫أضف إجابة

تصفح
تصفح

مجهول يجيب