In riferimento al suggerimento di Ciro78, potresti gestire il click con onclick() dall'html, oppure gestire il tutto dallo script con il più attuale addEventListener().
vecchio stile:
nuovo stile:codice:<img src="luna.jpg" alt="" border="0" height="380" width="380"> <button onclick="getNameOfImage(this)">luna</button> <img src="sole.jpg" alt="" border="0" height="380" width="380"> <button onclick="getNameOfImage(this)">sole</button> <script> let foto = null const getNameOfImage = (e) => { foto = e.textContent console.log(foto) } </script>
codice:<img src="luna.jpg" alt="" border="0" height="380" width="380"> <button class="btn">luna</button> <img src="sole.jpg" alt="" border="0" height="380" width="380"> <button class="btn">sole</button> <script> const btn = document.getElementsByClassName('btn') let foto = null const getNameOfImage = (e) => { foto = e.target.textContent console.log(foto) } Array.from(btn).forEach(e => { e.addEventListener('click', getNameOfImage) }) </script>

Rispondi quotando