I’m creating multiple arrows that rotate when clicked. However, I’m getting an error "div.addEventListener is not a function" when using an addEventListener. Is there a way to make this work? Thanks in advance for any help.
(function (document) {
var div = document.getElementsByClassName("container");
var icon = document.getElementsByClassName("arrow");
var open = false;
div.addEventListener("click", function () {
if (open) {
icon.className = "fa fa-arrow-down";
} else {
icon.className = "fa fa-arrow-down rotate";
}
open = !open;
});
})(document);
.fa-arrow-down {
transform: rotate(0deg);
transition: transform 1s linear;
}
.fa-arrow-down.open {
transform: rotate(180deg);
transition: transform 1s linear;
}
<div class="container">
<i class="fa fa-arrow-down arrow"></i>
</div>
<div class="container">
<i class="fa fa-arrow-down arrow"></i>
</div>
<div class="container">
<i class="fa fa-arrow-down arrow"></i>
</div>
2
Answers
The
getElementsByClassName()
method of Document interface returns an array-like object of all child elements which have all of the given class name. It returns array like object, so way of accessing thatdiv
should be like accessing certain element of array.You can use
for
loopHere’s ES6 example of
forEach()
loopYour issue was caused by you trying to bind event to an array instead of the element due to getElementsByClassName will return HTMLCollection which is type of array.
You can refer this answer which explained why bind event to array was not working.
I assuming you are using Vanilla JS only, first get all the elements which you want trigger the click event by class name, which is
container
class:Then you have to loop though these divs:
And here only you bind "click" event to your div, following code will find the
arrow
class elements in thecontainer
class and toggle theopen
class.Demo: