// Get a reference to the link
var myDomainLink = document.getElementById('my-domain-link')
// ... and to the image child element
var image = myDomainLink.querySelector('img')
// Then listen to the click event
myDomainLink.addEventListener('click', function () {
// When that event gets triggered, change the image source
image.src = 'my_other_image'
}, {
// Unless we want to change the image again upon further
// clicks, we only need to listen to the event once
once: true
})
You’d need to give them a specific class then, say image-link. Then you have two options: either get all those links like
var links = document.querySelectorAll('.image-link')`
then iterate over them and bind an event listener to each as shown above. Or you bind a single event listener to a common parent element (in case of doubt, just document.body) and check if the event.target matches that class:
document.body.addEventListener('click', function (event) {
var image
if (event.target.matches('.image-link')) {
image = event.target.querySelector('img')
image.src = 'my_other_image'
}
})
This pattern is called event delegation; an event dispatched from a given element bubbles up the DOM and sequentially triggers the same event on all of its ancestors, so you don’t have to add listeners to all the target elements themselves.
PS:
Ah yes, good point! (Would have to be camel-cased though…)