0

I have following code

let cardwrap = document.querySelectorAll(".portfolio-posts .t-entry-visual")
  window.addEventListener("scroll", () => {
      var top = window.pageYOffset / 62;
      cardwrap.style.transform = 'translate3d(0px, ' + top + 'px, 0px)';
  });

And my HTML

<div class="portfolio-posts">
   <div class="t-entry-visual"></div>
   <div class="t-entry-visual"></div>
   <div class="second-visual"></div>
   <div class="t-entry-visual"></div>
</div>

When I use querySelector I got the transform style working on the first .t-entry-visual element. But when I use querySelectorAll it doesn't apply the style on any element while I want the transform style applied on all .t-entry-visual elements.

CliffVandyck
  • 164
  • 11
  • 1
    querySelectorAll returns a collection of elements. You'll have to iterate over it and set style on each member. – AKX Jan 23 '22 at 14:38

1 Answers1

2

You have to iterate through it using forEach because querySelectorAll doesn‘t return an element but a collection of elements.

let cardwrap = document.querySelectorAll(".portfolio-posts .t-entry-visual");
window.addEventListener("scroll", () => {
  var top = window.pageYOffset / 62;
  cardwrap.forEach(function(elmt) {
    elmt.style.transform = 'translate3d(0px, ' + top + 'px, 0px)';
  });
});

See also:

user3840170
  • 26,597
  • 4
  • 30
  • 62
nare214
  • 337
  • 2
  • 7
  • Thanks for your answer. Where do apply forEach in the code? – CliffVandyck Jan 23 '22 at 14:44
  • But I would really recommend you not to copy and paste my answer but to try to understand, what I did :) – nare214 Jan 23 '22 at 14:48
  • While w3schools isn’t as bad as it used to be it is still full of inaccuracies and false informations. And it shouldn’t be used as a reference. – t.niese Jan 23 '22 at 14:55
  • @t.niese Oh really? Ok, I find it quite useful, but I‘ll update my answer – nare214 Jan 23 '22 at 15:22
  • The problem is that it is hard to figure out what information on w3schools are inaccurate and which not. For `forEach` it the `The forEach() method is not executed for empty elements.` is such an example. – t.niese Jan 23 '22 at 15:31
  • Ok, thanks for the tip, I'll reference to MDN in the future – nare214 Jan 23 '22 at 15:36