O'Reilly logo
  • Ahmed Elgendy thinks this is interesting:

Assigning the click handler to all images on the page

Here’s our first hurdle: in the current code we use the getElementById method to grab a reference to image “zero”, and assign the showAnswer function to its onclick property. Rather than hardcoding a call to getElementById for each image, we’re going to show you an easier way: we’ll grab all the images at once, iterate through them, and set up the click handler for each one. To do that we’ll use a DOM method you haven’t seen yet:


Cover of Head First JavaScript Programming


How to assign the same event handler to a set of elements that share either the tag name, class, id, or ...etc.?