@erenymo
Posted
Hi Patricia👋
To solve your problem, please look at event delegation concept.
Marked as helpful
Javascrip: I would like to simplify the 5 functions with an event ( "click") in just one if is posible. Could you help me with that?
Thanks a lot to everyone who spend time on reading me!!
@erenymo
Posted
Hi Patricia👋
To solve your problem, please look at event delegation concept.
Marked as helpful
@better5afe
Posted
Hi Patricia!
Firstly, congratulations on completing this project! I hope you had a lot of fun while making it! :)
To answer your question, there are two possible ways to shorten the event functions code:
standard for loop:
for (let i = 0; i < rate.length; i++) { rate[i].addEventListener("click", () => { valor = rate[i].innerHTML; }); }
forEach loop - it can be used as elements returned by the getElementsByClassName
method are stored in a HTML Collection, which behaves similarly to an array:
rate.forEach((element, i) => { element.addEventListener("click", () => { valor = rate[i].innerHTML; }); });
Hope it helps!
Happy coding! 🎃
Marked as helpful
@Patixi
Posted
@better5afe thanks a lot! The first solution was what i was looking for!! I tried both but the second one send me an error (rate.forEach is not a function). Anyways you helped a lot!
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord