I'm using the following js code to rotate various elements on scroll. It works perfectly fine as long as I getElementById. However, there is one image that I would like to rotate that does not have id. Instead, it has several classes. Naturally, I replace getElementById with getElementsByClassName. The problem is that whenever I do that, the code does not work.
Here is the working code:
<img src="url" id="logo">
<script>
var example = document.getElementById("logo");
window.addEventListener("scroll", function() {
example.style.transform = "rotate("+window.pageYOffset/10+"deg)";
});
</script>
Here is the non-working code:
<img src="url" class="circle">
<script>
var example = document.getElementsByClassName("circle");
window.addEventListener("scroll", function() {
example.style.transform = "rotate("+window.pageYOffset/10+"deg)";
});
</script>
P.S. I do not have access to HTML.
Looking the documentation you can check that while Document.getElementById
return an Element
calls to the Document.getElementsByClassName
method return an HtmlCollection
collection. You can then select the first element of the collection if it is the one you are looking for:
var example = document.getElementsByClassName("circle")[0];