0

How can I assign a JS function to a list of tag that are generate with a loop in HTML

Hello, I have a loop in my twig file : {% for child in listPositionRobot %} <h2 class=" accordion__items active" id="idbot"> Luna {{ child.getRobotName() }}</h2> {% endfor %} I would like to assign a JS function to all the h2 that are generate with this for loop. How can I do that ? Thank you.

6th May 2022, 6:07 PM
Siyam
Siyam - avatar
5 Réponses
7th May 2022, 2:47 AM
Calviղ
Calviղ - avatar
0
Thank for your answer. According to your advice, if I do this : let h2 = document.getElementById("idbot"); h2.addEventListener("click", linkToMarker); function linkToMarker() { document.getElementById("idbot"); //do something } linkToMarker(); Is this suppose to works ?
6th May 2022, 6:26 PM
Siyam
Siyam - avatar
0
Siyam After I have tried out Twig templating engine, I think I finally got what you meant by "assign a JS function to all h2". For all of the templating engine I have tried (mustache, ejs, handlebar, underscore and twig), I found that we can't assign JS function to all the template script, it only accepts object constant output, the JS function would not just be executed at all after it forms the html codes. However we can get around the issue by assigning the JS function to the object value. for example, instead of setting getRobotName() to the template directly, we can set a getRobotName object and set the object as {getRobotName: getRobotName()} Check out the example here https://code.sololearn.com/WZ6Lz3y5P3CR/?ref=app If you really want to run the JS function directly from the HTML element, the only way I can think of is to use React.js with jsx as templating. I apologize for I could not understand your question previously, I hope this time I can get it right then.
7th May 2022, 11:19 AM
Calviղ
Calviղ - avatar